Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In Django Rest Framework, how can the backend check if the files upload is multiple or not?
Client UI can either send a single file or a multiple files. When my backend receives it, I want to check whether it is a single or multiple files. If it is single, I just pass it straight (This is working already). But if it is a multiple files, I want to zip it first, and then pass it. I am stuck figuring out where Django Rest Framework do their validation. I tried both in Serializer and also in Views class CTDWorkSerializer(serializers.ModelSerializer): class Meta: model = CTDWork fields = ('wo_id', 'owner', 'created', 'purpose', 'work_type', 'reviewer', 'status', 'upload', 'download') read_only_fields = ('download',) def update(self, validated_data): print "foo" return validated_data and: class CTDWorkDetail(generics.RetrieveUpdateDestroyAPIView): queryset = CTDWork.objects.all() serializer_class = CTDWorkSerializer permission_classes = (permissions.IsAuthenticated, IsCurrentUserOrAdmin) parser_classes = (FormParser, MultiPartParser,) def perform_update(self,serializer,format=None): print "bar" I am thinking to use the request.FILES.getlist("files") in the views, but the server always reject the request before it can print something on my log. Any idea, why is it happened? Where and when does Django validate and reject the http request? Thanks -
How do I run SQL queries after a DB connection is established?
I want to run a command for the duration of the lifetime of the website. I don't want to run it more than once. Let's say I want to run the query: set names utf8mb4; Then I would just run something like: SomeRandomObject.objects.raw('set names utf8mb4;') Where should I put this? Does it matter what object I run the query on? Is there a better object? -
Django Many-To-Many Relationships between two models
I'm building a web app to help me manage my classes. So I have a Class model and a Student model and I want each Class to have multiple Students and I want each Student to be able to enroll in multiple Classes: class Class(models.Model): name = models.CharField(max_length=30) enrolled_students = models.ManyToManyField('Student', blank=True) ... class Student(models.Model): enrolled_classes = models.ManyToManyField(Class, blank=True) This works just fine but it's tedious. I create a class and then I create a student and add the enrolled class. And then I have to go BACK into the class and enroll the student. How do I automate this process so that Django automatically keeps track of which students are in which classes and which classes have which students enrolled? I'm sure there's something simple that I'm missing or not understanding. -
Should cache.close() be called using postgres as a Django cache backend?
Is it good practice to call cache.close() after each access to a Django cache stored in a PG database ? -
Command to open a new tab from django views
I have a submitting form, that on submit is doing some complex process and then in django views I have this: return redirect('match:finding', ...) Could I add something to views to make this redirection not on the page where submit form was completed, but in new tab? Like, leaving tab with form as it is, and then open a new window to continue the process. In html template it looks like this: <div class="form-input"> <input id="app-submit" type="submit" value="{% if credit_card %}Get Started{% else %}Loan{% endif %}"/> </div> I can't just add a/span tag with target="_blank" or window.open('url', 'new window') as the url will be generated after actually clicking submit button. -
Can't set attrs to add custom id or class name in IntegerField() widget in model form
I am trying to make a form in Django using model forms but i am facing a problem. Following is my code in forms.py which has an IntegerField(), I want to set a custom id and class for it but I'm not able to do so with the help of attrs in widget of IntegerField() whereas for CharField() it works. forms.CharField(widget=forms.CharField(attrs={'id': 'customID'})) works but hours = forms.IntegerField(widget=forms.IntegerField(attrs={'id': 'blah', })) doesn't. forms.py class TimerForm(forms.ModelForm): hours = forms.IntegerField(required=True, min_value=0, widget=forms.IntegerField(attrs={'id': 'blah', })) class Meta: model = Timer fields = ['hours'] Error in cmd: super(IntegerField, self).init(*args, **kwargs) TypeError: init() got an unexpected keyword argument 'attrs' -
Django: cannot get an Model instance from ForwardManyToOneDescriptor (ForeignKey)
I have the following code in accounts/signals/__init__.py: from django.db.models.signals import post_save from django.dispatch import receiver from orders.models import Order from accounts.models import Balance @receiver(post_save, sender=Order) def update_referral_balance(sender, **kwargs): if len(sender.user.referrals_set.all()): # TODO: Add referralTransaction new_referral_revenue = sender.user.referrals_set.get().revenue revenue_from_trade = \ new_referral_revenue - sender.old_referral_revenue balance, created = \ Balance.objects.get(user=sender.user, currency=sender.currency) balance.balance += revenue_from_trade balance.save() Now, when running tests I am getting the following error:====================================================================== ERROR: test_orders_with_approved_payments (payments.tests.test_views.PaymentReleaseTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/pipeline/source/payments/tests/test_views.py", line 75, in setUp self.order.save() File "/pipeline/source/orders/models.py", line 63, in save super(Order, self).save(*args, **kwargs) File "/usr/local/lib/python3.5/site-packages/safedelete/models.py", line 64, in save super(Model, self).save(**kwargs) File "/usr/local/lib/python3.5/site-packages/django/db/models/base.py", line 708, in save force_update=force_update, update_fields=update_fields) File "/usr/local/lib/python3.5/site-packages/django/db/models/base.py", line 745, in save_base update_fields=update_fields, raw=raw, using=using) File "/usr/local/lib/python3.5/site-packages/django/dispatch/dispatcher.py", line 192, in send response = receiver(signal=self, sender=sender, **named) File "/pipeline/source/accounts/signals/__init__.py", line 9, in update_referral_balance if len(sender.user.referral_set.all()): AttributeError: 'ForwardManyToOneDescriptor' object has no attribute 'referral_set' And indeed, when running through it in debugger, I see that the sender.user attribute is something of instance ForwardManyToOneDescriptor: ipdb> pprint(sender.__dict__['user'].__dict__) {'cache_name': '_user_cache', 'field': <django.db.models.fields.related.ForeignKey: user>} What am I doing wrong? -
Show private git repositorys in Django homepage.
I have a private git server, and a Django homepage. Are there any shortcutes to show the git repos in the Django framework. Or do you have to do all the work? -
The connection "database" doesn't exist Django, CentOS7, NGINX, UWSGI
Hello stackoverflow community, I have a problem. I'm running a CentOS 7.2 server with UWSGI serving my django app. However, after much troubling and config problems I managed to get it to start up. However, it shows the login page, and then 500 errors out. The 500 error is because it can't connect to a table "auth_user". I have a database and I've connected to it using the databases parameter in settings.py, however it is empty. When I run python manage.py migrate --database="mydatabasename" it gives me an error that says "django.db.utils.ConnectionDoesNotExist: The connection "databasename" doesn't exist" I've spent the last week looking at it and I can't seem to discover what is happening. The database exists and if I run "python manage.py shell", then I import MySQLdb, and connect to the database with the exact same parameters (still localhost), it works perfectly fine and it can connect with no issue. Does any experts know what is happening and why there is not a database connection? I have installed mariadb and then of course the secured setup for mysql. I've created the database and assigned a user/password to it. I can login with the username and password as well via mysql … -
django import-export "NOT NULL constraint failed"
I'm pretty new at Django and am stuck trying to implement Django import-export. My three pertinent model are Officer, Incident, and Details. Officer and Incident are in a M2M relationship through Details. I have gotten all of the functionality to work besides importing details. When I try to import via the import button, I get "NOT NULL constraint failed: police_archive_details.incident_id" for each row in the .xls or .csv file I'm importing. Here's my (current) admin.py from django.contrib import admin from import_export import resources, widgets, fields from import_export.admin import ImportExportModelAdmin, ImportExportActionModelAdmin from forms import AdminTextForm, OfficerTextForm from .models import Officer, Incident, Details, SiteText class FullNameForeignKeyWidget(widgets.ForeignKeyWidget): def get_queryset(self, value, row): return self.model.objects.filter( first_name__iexact=row["first_name"], last_name__iexact=row["last_name"] ) class DetailsInlineAdmin (admin.TabularInline): model = Details extra = 5 class OfficerResource(resources.ModelResource): class Meta: model = Officer class OfficerAdmin(ImportExportModelAdmin): list_display = ('first_name', 'last_name', 'badge', 'department') search_fields = ['first_name', 'last_name'] inlines = [DetailsInlineAdmin] resource_class = OfficerResource form=OfficerTextForm class Media: js = ('//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js','/static/admin/js/admin/popup.js') class IncidentResource(resources.ModelResource): officer = fields.Field( column_name='officer', attribute='officer', widget=widgets.ForeignKeyWidget(Officer, 'badge')) class Meta: fields = ('officer',) model = Incident class IncidentAdmin(ImportExportModelAdmin): list_display = ('office','case_number') search_fields = ['case_number'] inlines = [DetailsInlineAdmin] resource_class = IncidentResource class DetailsResource(resources.ModelResource): officer = fields.Field( column_name='officer', attribute='officer', widget=FullNameForeignKeyWidget(Officer)) incident = fields.Field( column_name='incident', attribute='incident', widget=widgets.ForeignKeyWidget(Incident, 'case_number')) class … -
Git- made changes on a local branch, checkout out master, and master is now broken
I am working on a Python/ Django project, using Git to manage my version control. I recently made some changes on a branch called conceptCalendar3, and the changes I made broke my site. I committed the changes to that branch, and then checked out master, which, I had branched from in order to create the conceptCalendar3 branch. However, when I now to try to view my site from the localhost, on master branch (on which I have not made any changes since it was last working), I now get a message in the browser telling me that: This site can't be reached localhost refused to connect The Python console is displaying a lot of output with error messages that I've not seen before: File "/Users/.../Documents/Dev/moonhub/moon/moon/urls.py", line 27, in url(r'^costing/', include('costing.urls', namespace="costing")), File "/Users/.../.virtualenvs/moon/lib/python2.7/site-packages/django/conf/urls/init.py", line 52, in include urlconf_module = import_module(urlconf_module) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/init.py", line 37, in import_module import(name) File "/Users/.../Documents/Dev/moonhub/moon/costing/urls.py", line 2, in from . import views File "/Users/.../Documents/Dev/moonhub/moon/costing/views.py", line 2900, in from projects.views import get_project_folder File "/Users/elgan/Documents/Dev/moonhub/moon/projects/views.py", line 38, in from .forms import * File "/Users/.../Documents/Dev/moonhub/moon/projects/forms.py", line 1207, in class PostDepMeetingForm(ValidatedForm): File "/Users/.../.virtualenvs/moon/lib/python2.7/site-packages/django/forms/models.py", line 257, in new raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (meeting_date_time) specified for Survey The 'fieldthat it seems … -
Django vs ASP.NET for developing Android app with real-time features
I am planning enterprise project development, and I am trying to choose between Django and ASP.NET. The web site should interact with Android app on real-time basis. For example, if someone receives an sms on his mobile phone, a real-time notification should be received on the web-page with detailed info on the received message (sender number, sms content, time received, etc). Besides this, I want to have a live chat on my web-page. Since this is my first experience of developing such apps, I am very much worried that Django can turn out not to provide necessary tools to implement this. AFAIK, there are several choices to implement both of the above-described real-time notifications, namely: signalr firebase websockets Django channels The question is: Does Django provide tools for real-time interaction with Android ? If the asnwer to question 1 is yes, then is there more than one technique available, or there's only one mature and well-supported solution If there are multiple solutions, then what are the known cons and pros of using each of them? And what is the best choice ? Can this technique - if it exists - only provide real-time interaction with the outside world, or it … -
Migrating to existing database without matching migration
I am working on a website in Django 1.9.8, and am trying to deploy an updated version of it to a server to demo it. As I have been learning Django as I develop this, I have made the mistake a few times of deleting my migrations and creating new ones when I run into database issues. This works fine on my dev when I am able to just delete an existing database, but is causing issues trying to get this deployed on the demo server without loosing the existing database data. I don't have the migration for the existing database schema on the demo server, and when I run manage.py makemigration <myappname>, it creates a initial migration for the app. When I attempt to run manage.py migrate <myappname>, it tells me that the tables already exist (because the migration is trying to add all of those tables, rather than do the modifications needed to be done on the database). Is there a way to create an initial migration based off of the current database, that I could then run makemigrations to get a migration that will modify the current database to be up to date with the current model? … -
Django JSON serializable issue when enabling memcache and page caching
I had to use memcached version django_bmemcached.memcached.BMemcached with Django 1.8. I think it uses a binary format. Anyway, when enabling this memecache on a particular page, and load this page, I immediately get TypeError: django.http.response.HttpResponse object at 0x106aceac8 is not JSON serializable Page view is loaded with typical return render( request, 'chart_detail.html', context ) Any clue why ? -
PIP install channels-> LINK : fatal error LNK1104: cannot open file 'MSVCRT.lib'
I am trying to install channels in Python 3.4 Django 1.10. But I encountered this problem when PIP installed twisted ( in Windows 10) C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\Bin\link.exe /DLL /no logo /INCREMENTAL:NO /LIBPATH:C:\Anaconda3\libs /LIBPATH:C:\Anaconda3\PCbuild\am d64 /EXPORT:PyInit_raiser build\temp.win-amd64-3.4\Release\src/twisted/test/rais er.obj /OUT:build\lib.win-amd64-3.4\twisted\test\raiser.pyd /IMPLIB:build\temp.w in-amd64-3.4\Release\src/twisted/test\raiser.lib /MANIFESTFILE:build\temp.win-am d64-3.4\Release\src/twisted/test\raiser.pyd.manifest LINK : fatal error LNK1104: cannot open file 'MSVCRT.lib' error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\B in\\link.exe' failed with exit status 1104 Is it because I have 32bit visual studio? Or there is not a Python c++ complier for Python 3.4? Any one has encountered and solved this problem? -
Local variable referenced before assignment but already imported and declared
local variable 'Document' referenced before assignment I keep on getting this variable unbound error but i do not seem to understand why. Importing it seems fine. I am using django 1-10 from django.shortcuts import render # Create your views here. from forms import DocumentForm from models import Document def SaveDocument(request): saved = False if request.method == "POST": #Get the posted form MyDocumentForm = DocumentForm(request.POST, request.FILES) if MyDocumentForm.is_valid(): print 'It enters here' Document = Document() Document.name = MyDocumentForm.cleaned_data["name"] Document.document = MyDocumentForm.cleaned_data["document"] Document.save() saved = True else: print 'Fails' else: MyDocumentForm = DocumentForm() return render(request, 'saved.html', locals()) -
Django: Superuser username doesn't show up in Users table
I am new to Django, and currently experimenting with creating a custom user. Apart from some additional fields that my custom user has, I implemented that email is used for authentication instead of username. Also, username is generated by concatenating first name, last name and a number so that unique username would be obtained. Now, I've checked the email authentication and username generation which seems to work, however, the problem that I face is when I enter the Django Administration panel and open User table instead of 'admin' username there is blank. Furthermore, other fields, such as first name, last name, etc don't show for all users. Screenshot of the admin panel Custom user and pre_save method for username generation (users.models.py): class User(AbstractUser): personal_no = models.CharField(verbose_name=_('personal number'), max_length=13) address = models.CharField(verbose_name=_('address'), max_length=50) @receiver(pre_save, sender=User) def generate_username_callback(**kwargs): instance = kwargs['instance'] if not instance.pk: instance.username = generate_username(instance.first_name, instance.last_name) def generate_username(first_name, last_name): val = "{0}{1}".format(first_name, last_name).lower() count = 0 while True: if count == 0 and User.objects.filter(username=val).count() == 0: return val else: new_val = "{0}{1}".format(val, count) if User.objects.filter(username=new_val).count() == 0: return new_val count += 1 if count > 10000: raise Exception("Too many users named {0}".format(val)) Custom backend for email authentication (users.backends.py): class EmailBackend(object): … -
AngularJS can't find components when using IIFEs
The angularjs style guide recommends using IIFEs to wrap angular components. However when I try to wrap mine as per the example, I run into the problem of them being "hidden" from angularjs and it is unable to load them page.html <script type="text/javascript" src="my-module.js" %}"></script> <script type="text/javascript" src="my-module-controller.js" %}"></script> <div ng-app="my.app" ng-controller="MyAppController"> {{ somevar }} </div> my-app.js (function() { 'use strict'; angular .module('my.app', []); }); my-app-controller.js (function() { 'use strict'; angular .module('my.app') .controller('MyAppController', MyAppController); function MyAppController() { .... } }); This results in the error: Uncaught Error: [$injector:modulerr] Failed to instantiate module my.app due to: Error: [$injector:nomod] Module 'my.app' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument. If I remove the IIFE on the module declaration so I'm left with the following: 'use strict'; angular .module('my.app', []); It works, to the extent that the next error is: Error: [ng:areq] Argument 'MyAppController' is not a function, got undefined If I remove the IIEF from the controller definition, everything works as expected. This is obviously a stripped down example, in the real project I am serving this page from a Django server, … -
Using Django URL's to send posted information to another page
I am new to Django, and I was wondering how I could use the URL's (or any other way) to send information from one webpage to another webpage. I tried making a global variable and return the information but it didn't work. In this example, I need to send the posted data for quote to the next page when the submit button is pressed. Here is my model: from django.db import models class OrderEntry(models.Model): quote_num = models.CharField(max_length=50, primary_key=True) customer = models.CharField(max_length=100) cust_po = models.CharField(max_length=50) datetime = models.DateTimeField(auto_now=True, editable=True) Form: from django import forms class Details(forms.Form): quote_number = forms.CharField(max_length=50, min_length=3) customer = forms.CharField(max_length=100) po_number = forms.CharField(max_length=50, min_length=4) View: from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponse from orders.models import OrderEntry, Items from orders.forms import Details, ItemDetails def entry(request): if request.method == 'POST': form = Details(request.POST) if form.is_valid: customer = request.POST.get('customer') quote = request.POST.get('quote_number') purchase = request.POST.get('po_number') obj_oe = OrderEntry(customer = customer, quote_num = quote, cust_po = purchase) obj_oe.save() return HttpResponseRedirect('/entry/items') else: form = Details( initial={'quote_number': 'QS', 'po_number': 'PO-'} ) return render(request, 'order.html', {'form': form}) def entry_items(request): if request.method == 'POST': form = ItemDetails(request.POST) if form.is_valid: # quote = quote value a1 = request.POST.get('i1') a2 = request.POST.get('i2') a3 = request.POST.get('i3') a4 … -
Python/ Django- add a text field to a form- populate it with a 'default value'
I am working on a Python/ Django project, and one of the fields on a form is currently broken (it's a datetimepicker field- the issue is that you can't select dates beyond 01/01/2017). It seems this is because the library being used to add the datetimepicker is no longer supported). I will look into implementing a datetimepicker myself, but urgently need to allow the user to select dates beyond the 01/01/2017 on this form- in order to save the dates & times for scheduled meetings, etc. My thoughts for the moment are to create a temporary fix, by adding simple EasyText fields to the form for the date/ time. I am aware that this means that the data entered will not be validated, so there is room for user input error, but it will enable the user to set dates/ times for meeting at least temporarily, until I fix the issue with the current datetimepicker field. The form that I want to add these fields to is defined in forms.py with: class PostDepMeetingForm(ValidatedForm): postdep_meeting_date = MoonDateTimeField(required=False, widget=forms.DateTimeInput(format='%d/%m/%Y %H:%M', attrs=({'class':'datetimepicker'}))) planning_who = forms.CharField(required=False) general_notes = EasyText(label='Survey notes') #ERF(16/12/2016 @ 1345) Add a text area for the meeting date & time meeting_date_time … -
Setting up Route53->CloundFront->Elasticbeanstalk infrastructure for Django stack
Lately, AWS introduced ability to connect Cloudfront(CF) to custom origins like Elasticbeanstalk thus enabling to CDN over dynamic servers with WAL in between. I want to use such kind of AWS infrastructure: Route53->CloundFront->Elasticbeanstalk(+LoadBalancer) and I also want to have non-zero TTL to cached requests to the same urls for anonymous users. Do do that I obviously need to whitelist cookies and perhaps headers to exclude for caching. Intuitively I feel that I need to exclude authorization cookies, csrf cookies - and the answer is which cookies and headers I need to exclude to make everything work? Also is there a gist/lib to tackle exclusion of CF ip address from X_FORWARDED_IP headers chain? I've found an article describing ho to set everything up for Ruby which is good enough but does not describe issues related to caching only general infrastructure set up. -
Django no module registration.supplements
I am trying to use the django-inspectional-registration and somehow I think I have deleted a file. I follow the tutorial and when I run the project I get an error window in the manage.py file at: execute_from_command_line(sys.argv) The error says no module registration-supplements found. I have tried to install all the packages to make sure I have everything but I think this is missing. I am using visual studio 2015 and installing packages with pip doesn't work in the virtual environment as it says something no module pip main and errors out, so I have used easy install instead and that seems to work. I have the package appearing in my virtual environment list. Just to be sure I also installed it in the python 3.5 environment as well. I can see the registration.supplements source code on the docs site here : http://django-inspectional-registration.readthedocs.io/en/latest/_modules/registration/supplements.html and I could just copy and paste but I'm not sure a)if that will even work and b) where to put it. I have done a search within my project and I can't find the file that shows this code so I'm fairly sure I just don't have it. So I think I am either missing the … -
how to put % in string in django
I have tried using '%%' and '%' already, none of these working in the below scenario. My custom lookup code is as follows: class MyCustomLookup(Lookup): lookup_name = 'custom_lookuptest' def as_sql(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) params = lhs_params + rhs_params return 'UPPER(%s) LIKE UPPER(%s)' % (lhs, rhs), params The output of query is: UPPER('field') LIKE UPPER('string') But I want the output as: UPPER('field') LIKE UPPER('%string%') -
run django in docker container
I'm trying to make a simple example of Django app running in docker container. using this image https://hub.docker.com/_/django/ just for simplicity. Don't tell me please that i shouldn't use it in production :) app is very simple and i'm ok with using very basic Django server. So, the problem is i'm always getting this error when trying to run the container image C:\Users\slipo\PycharmProjects\simple_blog>docker run -p 8000:8000 my-blog python: can't open file './manage.py runserver 0.0.0.0:8000 --settings=mysite.settings.prod': [Errno 2] No such file or directory however, ./manage.py and mysite.settings.prod both definitely existing in container. container creation log showing the file exists: Step 7 : RUN ls -a ---> Running in 932ed2ad3e4c . .. .idea Dockerfile blog manage.py mysite requirements.txt templates ---> e7f938c1cbf2 Removing intermediate container 932ed2ad3e4c Step 8 : CMD python ./manage.py runserver 0.0.0.0:8000 --settings=mysite.settings.prod ---> Running in f99bcafbc269 ---> aca534e9ccb6 Removing intermediate container f99bcafbc269 Successfully built aca534e9ccb6 Dockerfile: FROM django EXPOSE 8000 ADD . /simple_blog WORKDIR /simple_blog RUN pip install -r requirements.txt RUN pip install django-tinymce RUN ls -a CMD [ "python", "./manage.py runserver 0.0.0.0:8000 --settings=mysite.settings.prod" ] Thank you. -
DateTimeField is not defined error in django
I want to delete the videos from my models whose age is more than one day. models.py from __future__ import unicode_literals import urllib from django.core.files import File from django.db import models from PIL import Image from datetime import datetime from django.utils import timezone import os class video(models.Model): video_title = models.CharField(max_length=250) video_link = models.CharField(max_length=250) video_thumbnail = models.ImageField(upload_to = '',blank = True) image_url = models.CharField(max_length=250,blank = True) upload_date = models.DateTimeField(blank=True) def cache(self): if self.image_url and not self.video_thumbnail: result = urllib.urlretrieve(self.image_url) self.video_thumbnail.save( os.path.basename(self.image_url), File(open(result[0])) ) self.save() def __str__(self): return self.video_title + "," + self.video_link + "," + str(self.upload_date) In the shell, I do a query to delete the videos whose age is more than a day as follows: video.objects.filter((datetime.datetime.now() - (upload_date)).total_hours > 24) But I get the following error: In [6]: video.objects.filter((datetime.datetime.now() - (upload_date)).total_hours > 24) --------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-6-0c1ffc162513> in <module>() ----> 1 video.objects.filter((datetime.datetime.now() - (upload_date)).total_hours > 24) NameError: name 'upload_date' is not defined Why I am getting the error?