Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Updating Page with Form and Django Backend
I am working on a web-app thats is served by HTML/JS/CSS on the front-end and a Django/Python Backend. What I am aiming to do is to live update the front-end page based on some input from the user into a HTML form that will then be passed to the backend in a jquery ajax form. At this point the backend will manipulate that data passed in the form and then return the new data to the jquery request from where I can edit the page without having to reload. However, when I am trying to do this, the page is getting redirected to my post url. How do I go about passing the data back from the backend to the frontend without causing the page to reload or redirect. Here is what my code looks like so far: Frontend jquey ajax form: $('#InputForm').on('submit', function(event){ event.preventDefault(); console.log("form submitted!") $.ajax({ url : "/friendData/", // the endpoint type : "POST", // http method data : { friend : $('#FriendInput').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() }, // data sent with the post request // handle a successful response success : function(json) { $('#FriendInput').val(''); // remove the value from the input console.log(json); // log the returned json to … -
How to solve "ModuleNotFoundError: No module named 'social_django'" when deploying to Heroku?
I have Django App that works on LocalHost but when I try to deploy Heroku, I get this error of ModuleNotFoundError: No module named 'social_django'. I have this for my settings.py, I have installed social-auth-app-django through pip3. I have run manage.py migrate as well with no issues. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'whitenoise.runserver_nostatic', 'crispy_forms', 'social_django', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'social_auth.middleware.SocialAuthExceptionMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] AUTHENTICATION_BACKENDS = [ 'social_core.backends.twitter.TwitterOAuth', 'social_core.backends.facebook.FacebookOAuth2', 'django.contrib.auth.backends.ModelBackend', ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # new! STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' pip freeze returns the following relevant material social-auth-app-django==2.1.0 social-auth-core==1.7.0 heroku logs returns app[web.1]: [2018-09-19 22:58:32 +0000] [10] [ERROR] Exception in worker process app[web.1]: Traceback (most recent call last): app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker app[web.1]: self.load_wsgi() app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 129, in init_process app[web.1]: worker.init_process() app[web.1]: self.wsgi = self.app.wsgi() app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi app[web.1]: self.callable = self.load() app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi app[web.1]: return self.load_wsgiapp() app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load app[web.1]: … -
Django Wagtail responsive images
Is it possible to create responive images that resize with the page in Wagtail? Currently I have this: {% for item in page.gallery_images.all %} <div class="pull-left img-responsive my-5"> {% image item.image original %} <p>{{ item.caption }}</p> </div> {% endfor %} but it does not become smaller in width and height when decrease the width of the page. -
Django localhost load
I am running Ubuntu container on windows 10 host. I installed Django on Ubuntu container and now when I run Django (python3 manage.py runserver) I cannot view Django logo on IE host browser. I tried loading browser with URL such http://localhost:8000, Ubuntu container IP on port 8000, but no luck. I could connect to container using curl either via localhost or container IP address. Please help. Thanks, -
Why does running manage.py runs calls in urls.py
I've created Django application which runs TCP server in background. And everytime I run eg. python manage.py migrate or python manage.py collectstatic it turns on this TCP server and hangs in terminal, I need to Ctrl+C this to stop. Is there any way to stop running this code when executing manage.py? My code is placed in urls.py and the TCP server starts in a Thread. -
How to change backgroud row color in Django Admin NOT DUPLICATED
I have a simple model that I list in the admin, there is a field: etapa which takes a couple of values: {1, 3, 4, 5, 50, 77}. I want to mark all etapa=50 rows in RED. This is not duplicated because I don't want to remark the text like in the posible "duplicated". I just want to fill the row background. models.py class Registro(models.Model): ensayo = models.ForeignKey(Ensayo) fecha = models.DateTimeField(blank=False) fecha.date_fileter = True presion = models.FloatField(blank=False, help_text="Presion", verbose_name="PRESION (Bar)", null=False) etapa = models.IntegerField(blank=False, help_text="Etapa", null=False) tempin = models.FloatField(blank=False, help_text="Temp IN", verbose_name="TEMP. IN (C)", null=False) libre1 = models.FloatField(blank=False, help_text="Libre 1", null=False) libre2 = models.FloatField(blank=False, help_text="libre 2", null=False) libre3 = models.FloatField(blank=False, help_text="libre 3", null=False) def __unicode__(self): return "%s" % self.fecha class Meta: verbose_name_plural = "Registros" enter code here I have a custom change_list.html Any idea? -
Django : Keeping filefield filled after failing validation
I am trying to upload two files and when the validation fails, I would like to have the form's file field kept filled. However, currently, it would clear the file field if validation fails. For example, before submitting files after submitting files What are some ideas to keep the file fields filled? -
Override save in Django causing infinite recursion error
(Django 2.0, Python 3.6, Django Rest Framework 3.8) I'm trying to override Django's save() method to post multiple instances when a single instance is created. I have a loop that changes the unique_id which I have saved as a randomly generated string, and the datetime value which is updated through another function called onDay(). My thinking was, that if I changed the unique_id each time I looped around, Django would save the instance as a new instance in the database. But, I keep getting back an infinite recursion error when I run it though. When I checked it with pdb.set_trace(), everything does what it's supposed to until I hit the save() value in the for loop. Once that happens, I just get taken back to the line if self.recurrent_type == "WEEKLY":. I've used super() in a similar way (without looping) to override the save() function for a separate model, and it worked as expected. I think there's just something I'm misunderstanding about the super() function. Here is what I have so far: Overriding save() def save(self, *args, **kwargs): if not self.pk: # if there is not yet a pk for it # import pdb; pdb.set_trace() if self.recurrent_type == "WEEKLY": LIST_OF_DAYS … -
how to configure swagger UI to allow user to entry multiple values for query string parameter
I am using django-rest-swagger==2.1.2 and djangorestframework==3.7.7 and I have a view that looks like this: class PendingRequests(generics.GenericAPIView): ... filter_backends = (PendingRequestsFilter,) def get(self, request): ... request_status = request.GET.getlist('status') request_start_date = request.GET.get('start_date') request_end_date = request.GET.get('end_date') ... and I have defined a filter like so: class PendingRequestsFilter(BaseFilterBackend): def get_schema_fields(self, view): fields = [ coreapi.Field(name="status", description="Statuses of the Requests", required=False, location='query', example='active'), coreapi.Field(name="status", description="Statuses of the Requests", required=False, location='query', example='pending'), coreapi.Field(name="status", description="Statuses of the Requests", required=False, location='query', example='inactive'), coreapi.Field(name="start_date", description="Start Date of the Request (YYYY-MM-DD)", required=False, location='query', example='2525-12-25'), coreapi.Field(name="end_date", description="End Date of the Request (YYYY-MM-DD)", required=False, location='query', example='2525-12-26'), ] return fields This results in my swagger UI for this view looking like this: But when I enter different status like so ... ... and click 'try it out' I get a Request URL that looks like this: http://myserver:4800/api/v1/sudorequests/requests/?status=pending&status=pending&status=pending Note that status=pending is repeated three times. I wanted to get a Request URL that looks more like this: http://myserver:4800/api/v1/sudorequests/requests/?status=inactive&status=active&status=pending -
Why does CheckboxInput return nothing when unchecked?
I have a Django form with a checkbox = forms.BooleanField(required=False) and in my views I try to get this with: if request.POST['checkbox'] == True: # DO SOMETHING else: # DO SOMETHING ELSE When the checkbox is selected everything works, but when it isn't it returns the error message MultiValueDictKeyError at /theForm/ and highlights the line with the if statement. It seems if the checkbox doesn't get checked it doesn't return anything even tho the Django Documentation for this element says it should return False. Normalizes to: A Python True or False value. How is this done right? I don't want to use a try: except:-function, as this is shouldn't throw an error! BTW: In the "POST" part of the error message everything else (other data from this form) is mentioned except for the checkbox field. -
Django- Redirect to the calling URL holding any form data inputted by the user
I have a form that is used to create records and update records. I am also using a separate table to hold attachments related to these records that are being created/updated. Adding attachments are easy because I dont require any parameters to create a new record but when I am deleting attachment records I was forced to create a separate <form> request to post to the Url handling the attachment deletion then I redirect back to the calling URL. Whenever this request is sent it deletes any modified form data on the form. So if they were filling out a form from scratch and needed to delete an attachment it would erase all the information on the form when the request is redirected back. Another example is if they are updating a record through the form and needed to delete and attachment it would re-display the information before the modifications happened. This has to be a common thing that people try to do so what am I not doing or doing the wrong way? If any more info is necessary please let me know. Views.py def remove_attachment(request, id): if request.method == 'POST': if request.path == reverse('requisition:remove_file_attachment', args=[id]): attachment = get_object_or_404(FileAttachments, … -
Object of type <Model> is not JSON serializable
If I have GFK like inheritance models of Assets (Asset.model having an asset_id, asset_name, and an Account, OneType.model, SecondType.model, all inheriting from the Asset model etc...), and I want to provide an API endpoint for all assets in my Account, I could have (not sure if this is convention) a property on the Account model that is a list that extends the different asset types: #Account model @property def assets(self): list = [] list.extend(self.onetype_set.all()) list.extend(self.secondtype_set.all()) … return list I would need a serializer for the account class AccountSerializer(serializers.ModelSerializer): # filter to assets for the user def get_queryset(self): return Account.objects.filter(organization=self.request.user) class Meta: model = Account fields = ('assets', ) and I assume for each of the asset types class OneTypeSerializer(serializers.ModelSerializer): class Meta: model = OneType fields = ('asset_id', 'asset_name',) class SecondTypeSerializer(serializers.ModelSerializer): … … but I keep getting an error: Object of type 'OneType' is not JSON serializable ( i understand the error means I need to get the model to be serialized into JSON, but I thought the model would call the model’s serializer….) The stack trace doesn’t seem to be helpful because of the internal workings of DRF’s Viewsets, but here it is: /usr/local/Cellar/python/3.6.5_1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py in default else: return list(iterable) # … -
Django: Multiple databases one without model
I have two databases. default has several models and works fine by itself. When I add another database, it tries to creates tables from default database in the new database also. the new database does not have any models. All I am using it is to make a direct SQL query. DATABASES = { 'default': { 'ENGINE': .. .. }, 'payments': { 'ENGINE': .. .. }, } -
Django DateTime not storing ISO 8601 with T/Z (letters), but spaces instead
So right now, my model is declared with serializers.DateTimeField(input_formats=["iso-8601"]) and the value I get when printing is: 2020-10-03 11:15:00+00:00 Ideally that'd be 2020-10-03T11:15:00+00:00 or even more ideally, if it doesn't require a ton of work, 2020-10:03T11:15:00Z How do I accomplish this? Or when its sent over the network/to front-end, does this happen automatically? -
Clean `ChoiceField` from Django Form
Model: class SocialGroup(models.Model): INDIVIDUAL = 'individual' INSTITUTE = 'institute' options = ((INDIVIDUAL, 'Individual'), (INSTITUTE, 'Institute')) level = models.CharField(choices=options, max_length=100) def __unicode__(self): return self.name class Meta: ordering = ['name'] Form: class GroupLevelForm(forms.Form): level = forms.ChoiceField(choices=SocialGroup.options) def clean_level(self): return self.cleaned_data['level'] When I call my form I do it like level = GroupLevelForm({level: 'Individual'}). So when I pass Individual I want individual back in my cleaned data but at this moment it's giving me Error. How can I do it? Thanks in advance! -
Template Render Shortcuts not showing any result
I am trying to pass a variable from pymongo on my views.py to a template. I am not getting any errors but neither is my code being rendered to my template. views.py: def getTheA(request): for x in mycol.aggregate([{"$unwind":"$tags"},{'$match': {'tags.tag.name':'A A',}},{'$project': {'url': 1, 'AR': 1, 'tags.tag.name': 1, 'tags.variables': 1, '_id': 0}},]): theURLs = x['url'] theNames = json.dumps(x['tags']['tag']['name']) theVars = json.dumps(x['tags']['variables']) context = {'theURLs' : theURLs} return render(request, 'templates/a.html', context) My HTML code is pretty simple. I am just trying to print a list of the urls: <ul> <li><b>URLSSSS</h1></b> {% for theURL in theURLs %} <li>{ theURL.theURLs } {% endfor %} </ul> My result: URLSSSS I am new to Django and MongoDb and can't seem to figure out where I went wrong. -
Python Django chartkick - sort order of elements in column chart
How can i sort the elements in a column chart with python? Concrete I have several posts with different times from 00:00 to 23:00. E.g. I have the following data set in my django views: post_times = [{'00:00': 3, '01:00': 0, '02:00': 8, '03:00':6,..., '23:00':1}] If I load this data as a column_chart with chartkick in my template with {% load chartkick %} {% column_chart post_times %} Now when the chart is loaded in the template the times are displayed in the wrong order like in this screenshot: column_chart I got the same problem with ordering by days from Monday to Sunday. Is there a way to order the output in my chart? The documentation for chartkick with python isn't really in detail and I'm not able to transfer the documentation for Ruby to Python. -
Django query set for objects related through a many to many
I have the following models: class Brand(models.Model): owner = models.ForeignKey(Account, on_delete=models.DO_NOTHING) name = models.CharField(max_length=128) class Product(models.Model): owner = models.ForeignKey(Account, on_delete=models.DO_NOTHING) brand = models.ForeignKey(Brand, blank=True, null=True, on_delete=models.DO_NOTHING) class Store(models.Model): owner = models.ForeignKey(Account, on_delete=models.DO_NOTHING) name = models.CharField(max_length=128) menu = models.ManyToManyField(Product) address = models.ForeignKey(Address, on_delete=models.DO_NOTHING, blank=True, null=True) class Address(models.Model): address_1 = models.CharField(max_length=255) address_2 = models.CharField(max_length=255, blank=True, null=True) city = models.CharField(max_length=255) I'm currently trying to get a list of all products available in a specific city (eg. "New York"). Since products is related through a ManyToMany as a menu in stores I'm not 100% sure what the most optimal way of running this query would be. Any direction is helpful! -
Django - how to set a default to request.session upon login?
I'm using request.session['url'] to store URL and use it to go back to a previous page in a couple of views in my django app. It works really well, except in one case... right after login, the request.session['url'] is empty as it gets only populated when using some views. so, if I go directly to a view that expect to find something in request.session['url'], it crash. Is there a way or a place to set a request.session['url'] = 'home' as soon as the user logs in? Thanks -
Django FormView and List of results
Can i pass a model in FormView? class TodoView(FormView): model = Branch queryset= Branch.objects.all() form_class = FormTodoAdd ... How can i list the results of Branch in my Template? {% for branch in object_list %} ## don't work {% for branch in queryset %} ## don't work {{ branch }} {% endfor %} -
python manage.py runserver not connecting
python manage.py runserver Is not running and this is this traceback I'm receiving: Traceback (most recent call last): File "C:\Users\David\Envs\ebdjango\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\David\Envs\ebdjango\lib\site-packages\django\core\management\commands\runserver.py", line 123, in inner_run self.check_migrations() File "C:\Users\David\Envs\ebdjango\lib\site-packages\django\core\management\base.py", line 427, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\David\Envs\ebdjango\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\David\Envs\ebdjango\lib\site-packages\django\db\migrations\loader.py", line 49, in __init__ self.build_graph() File "C:\Users\David\Envs\ebdjango\lib\site-packages\django\db\migrations\loader.py", line 207, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Users\David\Envs\ebdjango\lib\site-packages\django\db\migrations\recorder.py", line 61, in applied_migrations if self.has_table(): File "C:\Users\David\Envs\ebdjango\lib\site-packages\django\db\migrations\recorder.py", line 44, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "C:\Users\David\Envs\ebdjango\lib\site-packages\django\db\backends\base\base.py", line 255, in cursor return self._cursor() File "C:\Users\David\Envs\ebdjango\lib\site-packages\django\db\backends\base\base.py", line 232, in _cursor self.ensure_connection() File "C:\Users\David\Envs\ebdjango\lib\site-packages\django\db\backends\base\base.py", line 216, in ensure_connection self.connect() File "C:\Users\David\Envs\ebdjango\lib\site-packages\django\db\utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\David\Envs\ebdjango\lib\site-packages\django\db\backends\base\base.py", line 216, in ensure_connection self.connect() File "C:\Users\David\Envs\ebdjango\lib\site-packages\django\db\backends\base\base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\David\Envs\ebdjango\lib\site-packages\django\db\backends\postgresql\base.py", line 168, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\David\Envs\ebdjango\lib\site-packages\psycopg2\__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? … -
How to GET request if login_required in DJango
Here my API: @login_required @api_view(['GET']) def get_order(request): order_list = Order.objects.values("user_name", "user_surname", "order_date").all() return HttpResponse(json.dumps([x for x in order_list]) The problem is when i add @login_required, i'm trying to do a Postman GET request using BASIC authentication with username and password. If i remove the @login_required, i can perform a succesful GET request without auth in Postman. -
How to execute Django Query as string
I want to make a query in Django ORM like this: query_string = "optionA=True,optionB=True,optionC=True" data = ModelObject.objects.filter(query_string) This code is giving following error: Traceback (most recent call last): File "/root/hellomeets/.env/hellomeets/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/root/hellomeets/.env/hellomeets/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/root/hellomeets/.env/hellomeets/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/root/hellomeets/.env/hellomeets/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/root/hellomeets/.env/hellomeets/local/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/root/hellomeets/.env/hellomeets/local/lib/python2.7/site-packages/rest_framework/views.py", line 483, in dispatch response = self.handle_exception(exc) File "/root/hellomeets/.env/hellomeets/local/lib/python2.7/site-packages/rest_framework/views.py", line 443, in handle_exception self.raise_uncaught_exception(exc) File "/root/hellomeets/.env/hellomeets/local/lib/python2.7/site-packages/rest_framework/views.py", line 480, in dispatch response = handler(request, *args, **kwargs) File "/root/hellomeets/hellomeets/frontend/views.py", line 74, in post filtered_emails = HelloMeetsMailList.objects.filter(final_query) File "/root/hellomeets/.env/hellomeets/local/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/root/hellomeets/.env/hellomeets/local/lib/python2.7/site-packages/django/db/models/query.py", line 784, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/root/hellomeets/.env/hellomeets/local/lib/python2.7/site-packages/django/db/models/query.py", line 802, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "/root/hellomeets/.env/hellomeets/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1250, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/root/hellomeets/.env/hellomeets/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1276, in _add_q allow_joins=allow_joins, split_subq=split_subq, File "/root/hellomeets/.env/hellomeets/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1151, in build_filter arg, value = filter_expr ValueError: too many values to unpack I also tried eval() but it didn't work. Is there any way so that I don't need to write raw sql query -
How to auto-generate a sample Django application from a database schema?
I am evaluating frameworks for a Proof Of Concept application. This application will have a life-cycle of about 30 days, after which it will be either forgotten or entirely rewritten. I have determined that I want to auto-generate a sample app from existing database schemas, and then just tweak some aspects of the visual design. I have watched a demo of this being done on Ruby on Rails: it auto-generates a simple view and data entry form for each table in the database, with built-in pagination etc. I've also already determined that I need to use Python, not Ruby, for this project. So I came upon this question: Python on Rails? The answers there referred me to Django. So the question. How can I auto-generate a simple CRUD application from database schemas, using Django, similar to what can be done on RoR? What I have tried so far: Google Search "generate django app from db schema" Reviewed all the documentation referenced in How to create a sample django project? -
Elasticbeanstalk; Why do Django admin templates work in production even though it's not commited?
I'm working on Django Project. I deployed my app into elasticbeanstalk but admin site doesn't work. But I tried to do the official tutorial and the admin site's templates does work. I found out there's a difference between my project and tutorial. here is my project settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(APPS_DIR, 'templates'), os.path.join(BASE_DIR, 'venv/lib/python3.6/site-packages/django/contrib/admin/templates'), ], 'APP_DIRS': False, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] because my project structure is different from default. I changed the setting like this. here is default TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] and I'm curious why admin templates still works in production even though it's inside virtualenv folder and I didn't commit the folder into git. I have to copy the admin site's templates and move them into templates folder so it can be loaded. But I want to know better way if there is.