Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am making a calculator and this is returning null in all the cases
This is views.py and the value of c is getting displayed on the browser as null. num1 is the name of my first html textbox. Num2 is the name of my Second html textbox def calc(request): a=int(request.POST["num1"]) b=int(request.POST["num2"]) if 'add' in request.POST: c=a+b return c if 'sub' in request.POST: c=a-b return c if 'mul' in request.POST: c=a*b return c if 'div' in request.POST: c=a/b return c def calprint(request): c=calc(request) return render(request,"result.html",{"result":c}) this is the HTML where the method is post <form action="calc" method="POST"> {% csrf_token %} num 1 <input type="text" name="num1"><br> num 2 <input type="text" name="num2"><br> <input type="submit" value="add"> <input type="submit" value="sub"> <input type="submit" value="mul"> <input type="submit" value="div"> </form> This is the urls.py urlpatterns = [ path('',views.home,name='home'), path('calc',views.calprint,name='add') ] -
How to redirect to django siteframework site from view?
How can you redirect to a siteframework Site model in from a view? I tried: current_site = get_current_site(request) main_site = Site.objects.get(domain='example.com') if current_site.domain != main_site.domain: return redirect(main_site) I get the error: argument of type 'Site' is not iterable -
Regex in re_path django 3
My path seems to be incorrect. I would like it to give me an output of everything that comes after 'post/' in the path. How do I fix it? My urls.py is `from django.contrib import admin from django.urls import path, re_path from blog import views as blog_views urlpatterns = [ Path('post/', blog_views.post), re-path(r'^post(.*)/$', blog_views.post), Path('about/'. blog_views.about), Path('', blog_views.index), Path('admin/', admin.site.urls) ]` My views.py is `from django.shortcuts import render,get_object_or_404 from django.http import HttpResponse from .models import Post def index(request): posts=Post.objects.all() return render(request,'index.html', {'posts': posts}) def post(request, slug): print(slug) return render ('post.html',{'post': get_object_or_404(Post, slug=slug)}) def about(request): return render(request, 'about.html', {})` How can I match the views.py to the correct path in urlpatterns? -
Combine Together Select Class and Input Class
At the moment I have to select a value from the drop down list and then click the button Items Per Page. I don't want to have to click the Items Per Page button. I want to embed the functionality from the Items Per Page button into the 4 options (3,6,9,12) in the Select element. <form method="GET"> <input class="btn btn-primary mb-4 height" type="submit" value="Items Per Page"> <select class="btn btn-outline-primary mb-4 height" name="paginate_by" id=""> <option value="3">3 </option> <option value="6">6 </option> <option value="9">9 </option> <option value="12">12 </option> </select> </form> I have had a couple of attempts (including the two below) and don't think any of them have been remotely close. <option value="3" type="submit">3 </option> <option class="btn btn-primary mb-4 height" value="6">6 </option> I Googled the issue but did not find anything remotely along the right lines. Does anyone have any suggestions or links to documentation? -
Create Multiple Variables In A Loop Accessible To Another Loop, In Template
I have a deep, disgusting loop in my template (I don't think I can do this logic in my view as my template needs to access various parts of all models involved at various places under various conditions): {% for unit_data in user.student_unit_data.all %} {% if unit_data.unit_id == unit.id and unit_data.package_id == package.id %} {% for extra_data in unit_data.student_class_data.all %} {% if extra_data.class_number|add:0 == iteration|add:1 %} {% if extra_data.completed == True %} Yes {% else %} No {% endif %} {% endif %} {% endfor %} {% endif %} {% endfor %} Later in my code I need access to variables attached to extra_data (the inner-most part of that loop). I need to access the variable three times per loop (three different instances). I don't want to loop through that whole thing again to get those variables. How can I store those variables (three different values extracted before leaving the above code block) while I have access to them within this loop for later use? Thank you. -
form labels not showing on html with a crispy form
I cannot find a way to make the labels of a form showing up in the template. I have been looking for hours on stackoverflow on ways to do it and nothing works so far. The labels are not showing up. Maybe i have a mistake in my code somewhere but i am not able to to spot it. forms.py class Contact(forms.ModelForm): class Meta: model = contact fields = ['first_name','last_name','email','phone'] #labels = {'first_name':'First name','last_name':'Last name', 'email':'email', 'phone':'phone number'} def __init__(self, *args, **kwargs): super(Contact, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_show_labels = True self.fields['first_name'].label = "First name" self.fields['last_name'].label = "Last name" self.fields['email'].label = "email" self.fields['phone'].label = "phone number" html template: <p> {% trans 'Or fill out the form below' %}</p> </h2> <br> <br> <form method="POST" class="form-validate" id="contact"> {% csrf_token %} <a>{% crispy form %} <input type="submit" class="learn_more2" value={% trans 'Contact us' %} style="background-color:#36393f;color: #DB6574;margin:auto;display:block"></a> </form> -
Django - Filtering foreign keys using related properties
I'm trying to filter a table in django based on the selected category. The category field is equivalent to name. I can't wrap my head around filtering all the blogposts which link to that certain category id. I currently use this: category_posts = BlogPost.objects.filter(category=cats).order_by('-published') Which I could use without there being any foreign key. I am passing the string variable into the path How could I make this more efficient and use the foreign key that relates the table.. Something like this: category_posts = Blogpost.objects.filter(category__category__contains=cat) I don't know if I am complicating things, just confused The following are the 2 tables available: name='Category', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('category', models.CharField(max_length=200)), ('summary', models.CharField(max_length=200)), ('slug', models.CharField(default=1, max_length=200)), ], name='Blogpost', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=200)), ('content', models.TextField()), ('published', models.DateTimeField(default=datetime.datetime(2020, 7, 8, 20, 49, 14, 897634), verbose_name='date published')), ('slug', models.CharField(max_length=200)), ('category', models.ForeignKey(default=1, on_delete=django.db.models.deletion.SET_DEFAULT, to='blogposts.Category', verbose_name='Category')), ], -
Django-Haystack & Elasticsearch brake with queries containing special characters
So I've been trying to fix a bug that really annoys me: Django-Haystack & Elasticsearch queries are working with accents but it brakes everytime with queries containing special characters like dash - and apostrophes '. For example let's use Baie-d'Urfé as the query. Here's my code: forms.py class FacetedProductSearchForm(FacetedSearchForm): def __init__(self, *args, **kwargs): data = dict(kwargs.get("data", [])) self.ptag = data.get('ptags', []) self.q_from_data = data.get('q', '') super(FacetedProductSearchForm, self).__init__(*args, **kwargs) def search(self): sqs = super(FacetedProductSearchForm, self).search() # Ideally we would tell django-haystack to only apply q to destination # ...but we're not sure how to do that, so we'll just re-apply it ourselves here. q = self.q_from_data sqs = sqs.filter(destination=Exact(q)) print('should be applying q: {}'.format(q)) print(sqs) if self.ptag: print('filtering with tags') print(self.ptag) sqs = sqs.filter(ptags__in=[Exact(tag) for tag in self.ptag]) return sqs Using FacetedSearch in View.py class FacetedSearchView(BaseFacetedSearchView): form_class = FacetedProductSearchForm facet_fields = ['ptags'] template_name = 'search_result.html' paginate_by = 30 context_object_name = 'object_list' And my search_indexes.py class ProductIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField( document=True, use_template=True, template_name='search/indexes/product_text.txt') destination = indexes.CharField(model_attr="destination") #boost=1.125 # Tags ptags = indexes.MultiValueField(model_attr='_ptags', faceted=True) # for auto complete content_auto = indexes.EdgeNgramField(model_attr='destination') # Spelling suggestions suggestions = indexes.FacetCharField() def get_model(self): return Product def index_queryset(self, using=None): """Used when the entire index for model is … -
Getting an error: django.urls.exceptions.NoReverseMatch: Reverse for 'user_auth/index.html' not found
Building a simple Login and Logout functionality using Django 3.0.8 and Python 3.6.8 views.py from django.shortcuts import render from user_auth.forms import UserForm from django.urls import reverse from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect, HttpResponse def user_login(request): if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: login(request, user) return HttpResponseRedirect(reverse('index')) else: return HttpResponse("Account not found.") else: print("Someone Tried to login and failed") print(f"Username: {username} and Password: {password}") return HttpResponse("Invalid login Credentials") else: return render(request, 'user_auth/login.html', {}) @login_required def user_logout(request): logout(request) return HttpResponseRedirect(reverse('index')) project urls.py from django.contrib import admin from django.urls import path, include from user_auth import views urlpatterns = [ path('', views.index, name="index"), path('user_auth/', include('user_auth.urls')), path('admin/', admin.site.urls), path('logout/', views.user_logout, name='logout'), ] app urls.py from django.urls import path from user_auth import views app_name = 'user_auth' urlpatterns = [ path('register/', views.register, name='register'), path('user_login/', views.user_login, name='user_login'), ] Error: ... File "/Users/servify/Desktop/login_check/user_auth/views.py", line 54, in user_login return render(request, 'user_auth/login.html', {}) ... django.urls.exceptions.NoReverseMatch: Reverse for 'user_auth/index.html' not found. 'user_auth/index.html' is not a valid view function or pattern name. I'm able to understand that the error is in line: return HttpResponseRedirect(reverse('index')) and it wants correct url for index.html file. But I've … -
Change db_table dynamically
I have 7 similar tables. I want to create a single model without set a table name. And then make my queries look to different tables depending a var name. For example, create a Model named Customer. class Customer(models.Model): name= models.CharField(...) class Meta: managed = False And then make a query like: table_name = "table1" Customer.set_table(table_name) customers_table1 = Customer.objects.all() table_name = "table2" Customer.set_table(table_name) customers_table2 = Customer.objects.all() -
Adding page to Django admin portal without a model
In summary I am trying to create a new page in the Django admin portal without having a model to attach it to. Thus far the only pages I have seem to be based off of the models in my db. I am trying to go off of this doc example: https://docs.djangoproject.com/en/3.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_urls but have had no luck so far. It seems that this class/functions are never getting hit. For example, I have an app testapp, and it has the models Model1 and Model2. So in the Django admin site I can see a title testapp with a dropdown that shows the Model1 and Model2 pages. I want to add another page, Overview, which will show a weekly overview of information, but I do not have an overview model, and don't want to create one just for this. According to the link I referred to I should be able to access the page via /admin/myapp/mymodel/my_view/, however I get a path did not match error. '''class MyModelAdmin(admin.ModelAdmin): def get_urls(self): urls = super().get_urls() my_urls = [path("my_view/", self.admin_site.admin_view(self.my_view))] return my_urls + urls def my_view(self, request): # ... context = dict( # Include common variables for rendering the admin template. self.admin_site.each_context(request), # Anything else you … -
NoReverseMatch Error in django and I don't know how to fix it
I am getting a NoReverseMatch error saying that "Reverse for 'flight' with arguments '(1, '')' not found. 1 pattern(s) tried: ['flights/(?P<flight_id>[0-9]+)$']". How do I get rid of it? urls.py, in flights app from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("<int:flight_id>", views.flight, name="flight"), path("<int:flight_id>/book", views.book, name="book") ] urls.py, in project folder from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("<int:flight_id>", views.flight, name="flight"), path("<int:flight_id>/book", views.book, name="book") ] views.py in flights app (with the function I think is causing the error) from django.shortcuts import render from .models import Flight, Passenger from django.http import HttpResponseRedirect from django.urls import reverse def book(request, flight_id): if request.method == "POST": flight = Flight.objects.get(pk=flight_id) passenger = Passenger.objects.get(pk=int(request.POST["passenger"])) passenger.flights.add(flight) print(type(flight_id)) return HttpResponseRedirect(reverse("flight", args=(flight_id,))) -
How do I solve this regex problem in Django
I've constantly been trying out my code but I keep getting the same error. I want the page to load everything related to 'post' and I'm not quite good at regex. I'd really appreciate corrections to help me better my code ![1]This is the error message I getThis is my urls.py page This is my views.py pageThis are my posts but when I click on any I get a page not found(404) error message -
Is there any way to code app with Kivy and django
How can I create app with Kivy and django for Android? If possible, help me please...I've tried but it's confusing -
Showing a list of database entries
I want to show a list of the names of my database entries. These entries are of type FileField(). I am trying to show them in my html but nothing appears. Models.py class UploadedFile(models.Model): the_file = models.FileField() Views.py class Showing_File(ListView): model = UploadedFile template_name = 'index.html' context_object_name = 'the_uploaded_files_list' index.html {% for file in the_uploaded_files_list %} <h1> {{ file.the_file }} </h1> {% endfor %} -
How can i store images and video in Django files system by using GraphQL
Django models :- File = models.FileField(upload_to='videos/', null=True) Django schema :- from graphene_file_upload.scalars import Upload class Arguments: File = Upload() it doesn't work with this way. any suggestion ? *i'm using react in frontend and i send the file like this:- const selectedFile = event.target.files[0]; -
DRF: How to handle Facebook users alongside regular users?
I am creating an app with a backend powered by DRF. I want to create a custom user model that inherits from Django's User model, with the main addition being a required email address for account verification and a required phone number field for 2-factor authentication. The problem is my app also needs to support Facebook login as an alternative, and that those users do need to verify their email address or phone number. I want a way to manage both types of users in a way that works well with DRF's auth system, requiring email and phone for regular users, while not requiring them for Facebook users, but I am confused as to how to go about it. Any advice would be greatly appreciated. P.S. for base login/registration I am using Djsoer package, and I will likely use social-auth-app-django for Facebook login unless I find a better alternative. -
Django Ajax Post request
Error is: Forbidden (CSRF token missing or incorrect.): /tracker/ i try a URL : tracker, tracker/, /tracker/, http://127.0.0.1:8000/tracker/' I'm new to Django. I try many URL and I also try a Moesif CORS(Extention) console Error is: jquery-3.5.1.js:10099 POST http://127.0.0.1:8000/tracker/ 403 (Forbidden) send @ jquery-3.5.1.js:10099 ajax @ jquery-3.5.1.js:9682 (anonymous) @ (index):276 dispatch @ jquery-3.5.1.js:5429 elemData.handle @ jquery-3.5.1.js:5233 urls.py file: urlpatterns = [ path('', views.index, name="index"), path('preview/<int:id>/', views.preview, name="preview"), path('checkout/', views.checkout, name="checkout"), path('tracker/', views.tracker, name="tracker"), ] console.log('working') $('#trackerForm').submit(function(event){ $('#items').empty(); var formdata = { 'orderId' : $('input[name=order_id]').val(), 'email' : $('input[name=email]').val(), 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val() }; $.ajax({ type : 'POST', url : 'http://127.0.0.1:8000/tracker/', data:'formdata', encode: true }) .done(function(data){ console.log(data) updates = JSON.parse(data); if (updates.length > 0 & updates != {}) { for (i = 0; i < updates.length; i++) { let text = updates[i]['text']; let time = updates[i]['time']; mystr = `<li class="list-group-item d-flex justify-content-between align-items-center"> ${text} <span class="badge badge-primary badge-pill">${time}</span> </li>` $('#items').append(mystr); } } else { mystr = `<li class="list-group-item d-flex justify-content-between align-items-center"> Sorry, We are not able to fetch this order id and email. Make sure to type correct order Id and email</li>` $('#items').append(mystr); } }) event.preventDefault(); }) Views.py def tracker(request): if request.method == "POST": order_id = request.POST.get('order_id') email = request.POST.get('email') try: order = Order.objects.filter(order_id=order_id, … -
Why the data sent through AJAX is being stored in request.body rather then request.POST and request.FILES in Django
I'm trying to send some data and multiple files to Django using AJAX, but the problem is the request.POST and request.FILES objects are empty and there is some data in request.body. var uploadFiles = []; var counter=0; function delete_row(no) { var query = $("#row"+no+"") var filename = query.find(".file-name").html(); if( confirm("Do you want to delete file '"+filename+"'?") ){ for(var i=0;i<uploadFiles.length;i++) if( uploadFiles[i].name == filename ){ uploadFiles.splice(i,1); break; } query.remove(); } alert(temp) } $(document).ready(function(){ document.getElementById("duedate").flatpickr({ enableTime: true, minDate: "today", }); $('#addButton').click( function(){ $('#files').click(); }); $('#submit').click( function() { var filesData = new FormData(); for(var i=0;i<uploadFiles.length;i++) filesData.append('file', uploadFiles[i]); $.ajax({ headers: { 'X-CSRFToken': '{{ csrf_token }}' }, url: "{% url 'Teacher:AddAssignment' %}", type: 'POST', enctype: "multipart/form-data", dataType: 'json', data: { 'csrfmiddlewaretoken': '{{ csrf_token }}', 'subjectid': $('#subjectid').val(), 'title': $('#title').val(), 'description': $('#description').val(), 'duedate': document.getElementById('duedate').value, 'data': filesData, }, contentType: false, processData: false, success: function(msg){ console.log(msg); }, error: function(ThrowError){ console.log(ThrowError); } }) }); }); Can anyone tell me what changes I have to make so I can access data using request.POST and request.FILES object. Alternatively I also would like to know how to save files and access data using request.body. I'm new to Django so don't have much idea about this. Also one weird thing was in this particular … -
user field is not migrating over to my postgres from sqlite3
I am attempting to migrate over my sqlite3 to postgres and I'm running into a ton of issues. Now I'm having an issue where one of my user fields, 'receiver' from my instant_message class is not found because it didn't migrate over to my postgres. How can I get it to migrate over correctly? error column dating_app_instantmessage.receiver_id does not exist LINE 1: ..."__count" FROM "dating_app_instantmessage" models.py/instant_message class InstantMessage(models.Model): sender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name= 'sender',on_delete=models.CASCADE ) receiver = models.ForeignKey(settings.AUTH_USER_MODEL, related_name= 'receiver',on_delete=models.CASCADE ) conversation = models.ForeignKey(Conversation, on_delete=models.CASCADE) message = models.TextField() date = models.DateTimeField(verbose_name="Data creation",default=timezone.now, null=False) viewed = models.BooleanField(default=False, db_index=True) -
Method is waiting for asyncio to complete before moving to next line
I am trying to use the asyncio in my code. This is working, but the problem is I want my code to keep executing instead it keep waiting for the asyncio code to complete execution. In the current scenario my code keep waiting for the asyncio code result = asyncio.run(run()) to complete before moving onto the next line of code. I think my asyncio code needs to be executed on the new thread. But how can I make it work? I am using Django. def Dashboard(requests): result = asyncio.run(run()) all_Farm = MyCollection.objects.all().filter(userid=requests.user.id) return render(requests, 'Dashboard.html', {'all_farm': all_Farm}) async def run(): drone = System() await drone.connect(system_address="udp://:14540") print("Waiting for drone to connect...") async for state in drone.core.connection_state(): if state.is_connected: print(f"Drone discovered with UUID: {state.uuid}") break print("Waiting for drone to have a global position estimate...") async for health in drone.telemetry.health(): if health.is_global_position_ok: print("Global position estimate ok") break print("-- Arming") await drone.action.arm() print("-- Taking off") await drone.action.takeoff() await asyncio.sleep(5) print("-- Landing") await drone.action.land() -
Why isn’t maths rendering inline - Django MathJax
I am trying to render maths with Django MathJax It works in display mode but not inline So $$ 2 ^ 3 $$ renders correctly However $ 2 ^3 $ doesn’t render at all Here’s the relevant settings.py: MATHJAX_ENABLED = True MATHJAX_CONFIG_FILE = "TeX-AMS-MML_HTMLorMML" MATHJAX_CONFIG_DATA = { "tex2jax": { "inlineMath": [ ['$','$'], ['\\(','\\)'] ], "processEscapes": True, } } -
Django - when overriding a model's save() function, should super() take any arguments?
Regarding the syntax for overriding a model's save() method, I've encountered a strange (to me, anyway) discrepancy between the Django official documentation, and numerous answers here on StackOverflow. I'm hoping someone can explain the difference I'm observing. Here's the example from Django's current official documentation: (source: https://docs.djangoproject.com/en/3.0/topics/db/models/#overriding-model-methods) class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() def save(self, *args, **kwargs): do_something() super().save(*args, **kwargs) # Call the "real" save() method. do_something_else() Note the call to super() -- it has no arguments. Now, for contrast, here's the syntax I keep finding in every search I've done on this same subject: that is, overriding the save() method of a django Model. There are too many examples to link, so I'm simply going to rewrite the above example code, using the exact syntax I've found in at least 6 different posts on the subject: class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() def save(self, *args, **kwargs): do_something() super(Blog, self).save(*args, **kwargs) # look at the arguments used here! do_something_else() The obvious difference: super() takes 2 arguments: the name of the Model ('Blog') and self. Is this simply a case of a recent(ish) Django update that made this syntax unnecessary? That seems the most likely explanation, but … -
HTML not rendering well when using markdown2 converted
I'm working on a Django project in Python and using markdown2 to convert some markdown text into HTML but it appears to not be doing it well or I'm missing something in the code. In my views.py file I'm using a custom function to extract some text from an .md file in markdown format and with the markdown2 module I try pass it on to the HTML template like so: text = markdown2.markdown(util.get_entry(entry)) But in the HTML, if I inspect the source code what is supposed to render as HTML comes out like this: &lt;h1&gt;HTML&lt;/h1&gt; Am I missing something in my code? Is the error on the HTML template or in my views.py file? Thanks in advance! -
Are Django redirect responses cached by default?
I have a url shortener and this is the view: def reroute(request, shorthand, parameter=None): .... #constructs url url = ... return HttpResponsePermanentRedirect(url) Basically I take in a url http://localhost:8000/silly-big-cat and route that to whatever the user supplied when this was created. The behavior that I started to notice was that the browser would hit the server once, if I went to that link again the browser somehow remembers where it was redirected last time and I see no indication of it hitting the server. Is the browser somehow caching this? If this is the case, is there a way to prevent this caching from happening? silly-big-cat's URL might change in the future but the browser may still be stuck with the old URL.