Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django virtual model pretending a real one
I need to move one of my Django apps into microservice, it's Files app, that have File and Folder models inside of it. Other apps using this app, and it's models to attach files to some other models, for example, User has "avatar" field, which is linked to a File model, Blog has "folders" field, which linked to a list of Folder models, and so on. Microservice would be accessible by REST API, and whould have methods for quering files and folders rich enought to satisfact all the needs of existing code. Now, to make my transition easier, I don't wont to change models, that are using my old File and Folder models. I want to create "virtual" models, named as File and Folder, that doens't have any tables in the database, and not the DjangoORM models at all. But they should mimic behavior of usual models, being just a "proxy" of "facade" to the REST API. So, it should be possible to use models as usual: # Quering files (this actually does request like GET files-service/api/files/all/filter?object_id=157&object_type=user): user_files = File.objects.filter(object_id=157, object_type='user').all() # Getting single file (this actually does request like GET files-service/api/files/7611): single_file = File.objects.get_for_id(7611) # Using linked object (avatar … -
Does django have some inbuilt model getter functionality? I've "lost" a function
I'm just.. I dunno. The model is calling self.get_next_by_context_start(). And it works. I can call it in a shell. But I've grepped the entire codebase and... it's just... not there. grep -r "get_next_by_context_start" - this lists just two instances of the string, both times where the function is being called. There's no def get_next_by_context_start anywhere. How am I being this stupid? How can I lose an entire function? -
What is the `_container` property of Django's http.response?
I can't find one good source that actually tries to explain it. The top 5 search results are just different links to source code. Right now, I'm trying to read a PDF that is being returned from a GET request, and I want to know why it's in response._container, when response is type HttpResponse. Is this PDF even what I'm looking for? Why is it the second element in the _container list? -
How send a Django User object using json to link a user to another model
I am pretty new to Django and am having trouble linking the current user to an auction item I am creating. I have read a load of articles but just can't get this working. The app has 3 models; the built in User model from django.contrib.auth.models, an Item model and an Auction model. The idea is that when an Item is created, it is linked to a User and a new Auction. I am using serializer classes from the django-rest-framework for the Item and the Auction that create the objects and save them in the database: serializers.py from rest_framework import serializers from .models import Item, Auction class ItemSerializer(serializers.ModelSerializer): def create(self, validated_data): item = Item.objects.create(**validated_data) return item class Meta: model = Item fields = '__all__' depth = 2 class AuctionSerializer(serializers.ModelSerializer): def create(self, validated_data): auction = Auction.objects.create(**validated_data) return auction class Meta: model = Auction fields = '__all__' depth = 1 models.py from django.db import models from django.contrib.auth.models import User from django.utils.timezone import now from datetime import date, timedelta class Item(models.Model): title = models.CharField(max_length=100) timestamp = models.DateTimeField(default=now, editable=False) condition = models.CharField(max_length=50) description = models.TextField() owner = models.ForeignKey( # is this the correct way to refer to the user if not using a custom … -
prefetch for a model with two m2m field to through model
i am using mysql and these are my tables: class Movie(models.Model): title = models.CharField(max_length=255) voice_languages = models.ManyToManyField('Language', through='LanguageMiddle', related_name='voice_language') subtitle_languages = models.ManyToManyField('Language', through='LanguageMiddle', related_name='sub_language') ... @classmethod def _check_m2m_through_same_relationship(cls): return [] class Language(models.Model): title = models.CharField(max_length=50, unique=True) title_en = models.CharField(max_length=50, blank=True) class Meta: db_table = 'language' class LanguageMiddle(models.Model): LANGUAGE_TYPE = ( (0, 'voice'), (1, 'sub') ) movie= models.ForeignKey('Movie', on_delete=models.DO_NOTHING) language = models.ForeignKey('Language', on_delete=models.DO_NOTHING) language_type = models.CharField(max_length=5, choices=LANGUAGE_TYPE) class Meta: db_table = 'language_middle' after reading this ticket and seeing that none of the solutions work for me i have added that class method. now when i try to use prefetch in my query like this: prefetch = Prefetch('subtitle_languages', queryset=LanguageMiddle.objects.prefetch_related('languagemiddle_set')) queryset = queryset.prefetch_related(prefetch) to get for each movie the related subtitle_languages and voice_languages but i will get the following error Cannot resolve keyword 'sub_language' into field. Choices are: movie, movie_id, id, language, language_id, language_type so i have changed languagemiddle_set with language__languagemiddle_set but it throws the same error . and for voice_languages it is also the same is this because of the hackish overriding that i am doing or i am doing something wrong here? -
can't understand django csrf exempt for cbv's code
i cant understand the meaning of the dispatch method and what is the method_decorator class CSRFExemptMixin(object): @method_decorator(csrf_exempt) def dispatch(self, *args, **kwargs): return super(CSRFExemptMixin, self).dispatch(*args, **kwargs) can you please answer this question? -
Django Rest Framework - "Unable to create account" with Djoser
I have some issue with User registration. I'm using library Djoser by Sunscrapers. During creating new User from Postman i get "Unable to create account" response. In my terminal (docker) I get following informations: ERROR: null value in column "country_id" violates not-null constraint DETAIL: Failing row contains (53, null, , t, jaroslawpsikuta1@gmail.com, pbkdf2_sha256$180000$p2Q8c4Du3uLF$o56YHGCS0ZutasVhevPXl8rrMG/VYL..., , null, , , , 2020-03-10 10:06:48.053201+00, null, f). STATEMENT: INSERT INTO "accounts_user" ("last_login", "email", "is_superuser", "is_active", "password", "first_name", "last_name", "date_of_birth", "description", "address", "phone", "created_at", "country_id") VALUES (NULL, 'jaroslawpsikuta1@gmail.com', false, true, 'pbkdf2_sha256$180000$p2Q8c4Du3uLF$o56YHGCS0ZutasVhevPXl8rrMG/VYLiyzTB6LrSY4ws=', '', '', NULL, '', '', '', '2020-03-10T10:06:48.053201+00:00'::timestamptz, NULL) RETURNING "accounts_user"."id" It seems like Djoser don't see my request body, and it's trying to put empty or null values into database. Till now, I tried following solution: Customize the djoser create user endpoint ...but it didn't work. Do You have any ideas how to resolve it? Maybe I forgot something? Thank You for help :) Best regards, -
how to add delete button in each row of my table?
How is going? I'm learning to programming in django. For the moment I'm building a simple app that utilizing a form update the referenced table. Now I'm try to add a delete button in each row of my table but, beside I have tried a lot of solutions, I didn't find one that works correctly. Below my code: urls from django.urls import path from app import views urlpatterns = [ path('', views.homepage, name='homepage'), #path('algo', views.PersonListView.as_view(), name='algo'), ] forms from django import forms from .models import Income class IncomeModelForm(forms.ModelForm): class Meta: model = Income fields = "__all__" tables import django_tables2 as tables from .models import Income class PersonTable(tables.Table): class Meta: model = Income template_name = "django_tables2/bootstrap.html" views from django.shortcuts import render from django.http import HttpResponse from django.views.generic import ListView from .models import Income from .tables import PersonTable from .forms import IncomeModelForm def homepage(request): table = PersonTable(Income.objects.all()) if request.method == 'POST': form = IncomeModelForm(request.POST) if form.is_valid(): print("Il form è valido") new_input = form.save() else : form = IncomeModelForm() context= {"form": form, "table":table } return render(request, "app/base.html", context) html {% load static %} {% load render_table from django_tables2 %} <!doctype html> <html lang="it"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" … -
NameError at /model/detect/
I am creating a Django project with one app for the moment. I have created a view inside the app and have tried to add url.py file inside the app folder. Secondly, I have also referenced the url.py file to the url.py file of the Djano Project. Now when I start the server and try to access the view from the browser I get the following error: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/model/detect/ Django Version: 1.8 Python Version: 3.7.6 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'model') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware') Traceback: File "/home/nauyan/anaconda3/envs/Django/lib/python3.7/site-packages/django/core/handlers/base.py" in get_response 119. resolver_match = resolver.resolve(request.path_info) File "/home/nauyan/anaconda3/envs/Django/lib/python3.7/site-packages/django/core/urlresolvers.py" in resolve 368. sub_match = pattern.resolve(new_path) File "/home/nauyan/anaconda3/envs/Django/lib/python3.7/site-packages/django/core/urlresolvers.py" in resolve 368. sub_match = pattern.resolve(new_path) File "/home/nauyan/anaconda3/envs/Django/lib/python3.7/site-packages/django/core/urlresolvers.py" in resolve 240. return ResolverMatch(self.callback, args, kwargs, self.name) File "/home/nauyan/anaconda3/envs/Django/lib/python3.7/site-packages/django/core/urlresolvers.py" in callback 247. self._callback = get_callable(self._callback_str) File "/home/nauyan/anaconda3/envs/Django/lib/python3.7/site-packages/django/core/urlresolvers.py" in get_callable 106. mod = import_module(mod_name) File "/home/nauyan/anaconda3/envs/Django/lib/python3.7/importlib/__init__.py" in import_module 127. return _bootstrap._gcd_import(name[level:], package, level) File "/home/nauyan/Desktop/EsperSolutions/SystemCodes/March2020/Face_Recognition_Django/model/views.py" in <module> 5. base_path=os.path.abspath(os.path.dirname(__file__))) Exception Type: NameError at /model/detect/ Exception Value: name 'os' is not defined Url.py file of App is: from django.conf.urls import include, url urlpatterns = [ url(r'^detect/', 'model.views.detect', name = 'detect'), ] Urls.py file of Django … -
How to pass uidb64 and token to email template from custom form in Django
I have a Django app, and I want to make a password restore page. I have custom form, which inherits from PasswordResetForm. PasswordResetForm can pass uidb64 and token to emails/restore.html by itself, but how to do this by myself in my custom form? Now Django says me: Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. 1 {% autoescape off %} 2 http://{{ domain }}{% url 'Authentication:password_reset_confirm' uidb64=uid token=token %} 3 {% endautoescape %} because I did pass nothing to the params. How do i pass the uidb64 and token? forms.py from django import forms from django.contrib.auth.forms import User, PasswordResetForm, SetPasswordForm ... class RestoreForm(PasswordResetForm): email = forms.EmailField(required=True) class Meta: model = User fields = ["email"] views.py def request_restore_password(request): if request.method == 'POST': form = RestoreForm(data=request.POST) if form.is_valid(): form.save(from_email=AdminEmail, email_template_name='emails/restore.html', request=request) return HttpResponse('123 for now') else: form = RestoreForm() return render(request, 'request_restore_password.html', {'form': form}) emails/restore.html {% autoescape off %} http://{{ domain }}{% url 'Authentication:password_reset_confirm' uidb64=uid token=token %} {% endautoescape %} -
I can't use django with python 3.7
My original python version is 3.6.9 >> I have installed 3.7 manually >> then I tried to use pipenv to create a virtual environment >> pipenv --python 3.7 every thing was fine until I tried to install django, I had this error and I don't know how to deal with it. ERROR: ERROR: Could not find a version that matches django If I created my virtual environment using python 3.6, every thing works just right. image of the error -
Chartjs draw line chart where line go back and forth (by chronological order)
So I want to draw a line chart where the line goes from point to point by chronological order but points can go back and forth so the line would have to go all directions not only right. I don't really know if this is possible but I haven't find any solution so far. I initialize a new line chart with null data and I pass through ajax a list of players (datasets) and each of them has a list of points with x and y in chronological order. For example: Data: [Player 1: [0,1][3,5][1,2], Player 2: [2,5][1,0]] I am now able to draw all the points to each dataset but the line follows the xaxis label order and not the one which I inserted the points. My code is the following: data.players.forEach( function(a, i) { console.log(a); chart.data.datasets.push({ label: a, data: [null], backgroundColor: get_color(i).background, borderColor: get_color(i).border, borderWidth: 3, fill: false, showLine: true, pointStyle: get_shape(i), pointRadius: 5, spanGaps: true }); data.default[i].forEach( function(e, j) { console.log(e); chart.data.datasets[i].data[e[1]] = e[0]; }); }); chart.update(); Hope someone knows how to solve it in case it is possible or maybe suggest another tool where it can be possible. Thanks and sorry for my english! -
'password1': None – password is always None on registration in Django UserCreationForm
I have been developing my project for several months. Registration has been working perfectly, but at some point it stopped accepting the password: the password is always saved as None and the user is saved into the database with password not set. I did not change anyhow either the form or the view working with sign-up, so I don't know where it comes from. My code is: forms.py class UserSignUpForm(UserCreationForm): username = CharField(max_length=35, required=True}) email = UnicodeEmailField(required=True) password1 = CharField(max_length=35, required=True, widget=PasswordInput) captcha = ReCaptchaField(error_messages={'required': 'Prove you are not a robot.'}) class Meta: model = User fields = ('username', 'email', 'password1') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) del self.fields['password2'] views.py class UserSignUpView(generic.CreateView): form_class = UserRegistrationForm template_name = 'accounts/registration.html' def form_valid(self, form): form.cleaned_data['password'] = form.cleaned_data.pop('password1') form.cleaned_data.pop('captcha', None) user = User.objects.create_user(**form.cleaned_data) ... return HttpResponseRedirect(reverse('account_activation_sent')) templates.py <div class="password"> <label for="{{ form.password1.id_for_label }}">Password</label> </div> {{ form.password1.errors }} {% render_field form.password1 placeholder="Enter your password" class="text-pass" %} My User model: class User(AbstractUser): username = CharField( max_length=150, unique=True, validators=[CustomUsernameValidator()],) email = UnicodeEmailField(blank=True) id = AutoField(primary_key=True) uid = UUIDField(default=uuid.uuid4, editable=False) email_confirmed = BooleanField(default=False) is_active = BooleanField(default=False) last_movie_seen = CharField(max_length=150, blank=True) associated_user = OneToOneField(AssociatedUser, on_delete=CASCADE, null=True, blank=True) The question is: why form.cleaned_data['password1'] always returns None and the user is … -
Django, RestAPI, Microsoft Azure, website, virtual machine, ubuntu
is there any chance somebody could point me in good direction in this problem: I have developed website and restapi using django and djangorestapiframework. On local machine they are working perfectly so my next step is trying to publish it on remote server. I chose microsoft azure (for some weird reasons and i cannot change it). I created a virtual machine with ubuntu server 18.04, installed everything to run my project there. While i run it locally on virtual machine it's working perfectly, at localhost:8000 my websiste and rest-api is showing. Now i want it to publish to the world so it can be accessed under IP of my virtual machine (azure) or some different addres so everybody can access it. I was looking through azure tutorials on microsoft website and google, but i cannot find anything working (I know i am really bad person at this). I don't want to use their microsoft webapp solution or windows server. It's need to be working with Ubuntu on virtual machine from Azure. Is it possible to do and if yes then how? Thank you a lot for your time and help :) BR, Me -
Django one database per user or one in general?
I'm currently writing a chat-application for my Website and storing all the Messages in one database, by referring to sender and receiver with a Foreign-key. Is this really the smartest Idea? I think the site could become slow when everybody is trying to access the same database or when the number of sent messages gets big. Would it be smarter/faster, to use one database per user, storing his/her messages there? If yes, am i right that this is not really possible to achieve this with Django? Thanks for your Answer! -
Querying Multiple Database on the same server with same table structure
I have a specific problem where I have to query different database to show results in dashboard. The tables that I have to query in those db are exactly same. The number of database can be max 50 and minimum is 5. NOTE: I can't put all the data in same database. I am using postgres and django. I am not able to understand how to query those database to get data. I also need to filter and aggregate and sort the data and show 10 - 100 results on the search query params. APPROACH that I have in mind Loop through all database and fetch the data based on the search params and order it by created date. After that take 10 - 100 results as per search params. I am not able to understand what should be the correct approach and how it should be done considering speed and reliability. -
How to embed matplotlib graph/figure on django
Can someone tell me how to embed matplotlib or send matplotlib graph from django views to the template?. I already try searching for the example code and still noone work or the code i copy is outdated. Then i try code like this one from django.shortcuts import render from django.http import HttpResponse, JsonResponse import matplotlib.pyplot as plt import io import numpy as np import urllib import base64 # Create your views here. def index(request): plt.plot(range(10)) fig = plt.gcf() buf = io.BytesIO() fig.saveFig(buf, format='png') buf.seek(0) string = base64.b64encode(buf.read()) uri = urllib.parse.quote(string) return render(request, 'home.html', {'data': uri}) and for the html code {% extends 'base.html' %} {% block content %} <h1>Hello</h1> <img src="data:image/png;base64,{{ data }}" alt=""> {% endblock %} when i run that code error message "'Figure' object has no attribute 'saveFig'" pop up on the browser. Maybe someone can help me to fix this code or show me the other way to do this -
Show Many to many field images in the admin page next to the field itself
First of all, after you read this question, feel free to suggest edits for the title cause I'm not sure what to type I have this hierarchy.. Stone -> Subtype -> Subtype -> Subtype and this goes as long as the Stone has a Subtype in real life. So it's not known how many times will I add Subtypes to a specific stone. Let's inspect it # models.py from django.db import models from django.utils.safestring import mark_safe class Stone(models.Model): name = ... sub_type = models.ForeignKey('StoneSubType', on_delete=models.DO_NOTHING ,related_name='stones', blank=True, null=True) class StoneSubType(models.Model): name = ... sub_type = models.ManyToManyField('self', related_name='sub_types', blank=True) class StoneSubtypeImage(models.Model): stone = models.ForeignKey('StoneSubType', on_delete=models.CASCADE, related_name='images') image = models.ImageField(default=None, upload_to='stone_subtypes/') class StoneImage(models.Model): stone = models.ForeignKey('Stone', on_delete=models.CASCADE, related_name='images') image = models.ImageField(default=None, upload_to='stones/') def image_tag(self): return mark_safe(f'<img src="{self.image.url}">') Let's go the admin page to illustrate what I want Now, Every Subtype has some images, and the Stone itself has some images of course, Images are as shown in the code, So I made them appear in the admin page as an Inline which is shown there when I scroll down. Like this Now, I want to show the images of the Subtype next to the Subtype field. Any suggestions on how can we … -
Must the update form in Django update all fields of an object?
I have created multiple update forms in my Django app. My question is: does Django need to update every single field of an object, or is there a way to only update fields that were actually changed? So, for example, I might have a form with Name, Mail, City. And I might use the update form to update my Mail. Does Django also need the Name and City form fields filled and then update, or is there a way to leave them blank and not update the database? -
django-allauth receiver signal to add group permission to user on signup
My goal is to add a new group to a user when they signup. I'm using the django-allauth package and it seems the best way to do this is to use the package defined signals. Not totally sure how to debug this as I have not been getting any error messages. signals.py from allauth.account.signals import user_signed_up from django.dispatch import receiver from django.contrib.auth.models import User from django.contrib.auth.models import Group #Group Added To New Users: "Can Add Pattern, Symbol, Broker" @receiver(user_signed_up) def user_signed_up_signal_handler(request, user): group = Group.objects.get(name='Can Add Pattern, Symbol, Broker') user.groups.add(group) user.save() -
How to disable TinyMce cdn for one textarea?
I'm using TinyMce as cdn how do I disable for a specific textarea. I see everyone is explaining to do the bellow code but I'm using as cdn. tinyMCE.init({ ... editor_deselector : "mceNoEditor" }); -
TypeError at /website/login/:login() takes 1 positional argument but 2 were given
I am creating a website using Django and i am a beginner in it. views.py: def login(request): if request.method == "POST": form = AuthenticationForm(data=request.POST) if form.is_valid(): user=form.get_user() login(request,user) if 'next' in request.POST: return HttpResponseRedirect(reverse(request.POST.get('next'))) else: return HttpResponseRedirect(reverse('website:books')) else: return render(request,'website/login.html') else: form=AuthenticationForm() return render(request,'website/login.html',{'form':form}) The error i am getting is: File "D:\playground\blog\website\views.py", line 16, in login login(request,user) TypeError: login() takes 1 positional argument but 2 were given [10/Mar/2020 14:34:57] "POST /website/login/ HTTP/1.1" 500 74342 What am i missing? -
HOW TO PASS AN ID IN DJANGO FORM INTO VIEWS
I've this django form and I am trying to pass an ID that are related to a specific record on my project,this is forms.py class AcademicForm(forms.ModelForm): class Meta: model=Academic fields="__all__" labels={ 'Average_grade':'Average Grade', 'Overall_position':'Overall Position', 'Total_number_in_class':'Total Number In Class' } Date = forms.DateField( widget=forms.TextInput( attrs={'type': 'date'} ) ) Here is my views.py and i don't know how to pass an ID ef add_academic(request): form=AcademicForm(request.POST) if form.is_valid(): form.save() return redirect('/child/more/') else: form= AcademicForm() context={ 'form':form } return render(request,'functionality/more/academy/add.html',context) Here is my urls.py urlpatterns=[ path('base',views.base,name='base'), path('index',views.index,name='index'), path('academic',views.add_academic,name='academy'), ] And this is my template by which form can be displayed {% extends 'base.html' %} {% load static %} {% load crispy_forms_tags %} {% block content %} <div class="container" style="margin-top:15px"> <div class="col-md-12"> <b> <p class="text-center" style="font-weight: 1000;font-size:25px">Add Student Here</p> </b> </div> <div class="container"> <div class="col-md-8"style="margin-bottom:20px"> <form action="" method="post" autocomplete="off"> {% csrf_token %} {{ form | crispy }} <input type="submit" value="Register" class="btn btn-primary btn-block"> </form> </div> </div> </div> {% endblock %} -
Creating a Django model that stores a randomly selected list of objects from another model
Summary: I'm creating an app that involves exams, categories and questions, each exam, when created, will query data from each catagory, each category will then return a pre-determined number of random questions from themselves Exam needs 25 questions from category A and 25 from category B. Category A and B both return 25 items each. The exam model needs to store these 50 items. I'm having trouble figuring out how to go about storing the returned data in the exam model. I know it's just gonna be question IDs but can I just store them in a string CharField? The number of questions per exam can get to around 200 and question IDs are expected to be around four to five digits in length too. Is there a better way to do this than storing it in a string? I can't store the selection criteria because I'm going to be using randomization/shuffling... I think the actual solution would be simple but I'm pulling my hair out trying to figure this out lol. Can I just use both ForeignKey and ManyToMany for Category-Question and Exam-Question? -
Django ModuleNotFoundError from Heroku stored files
Running a blog app within Django which has been working fine until now, encountering an issue when I try to utilize any of the manage.py functions (collectstatic, migrate, runserver etc). I had to retrieve this build from a previous git which was going to a Heroku dyno so I believe a lot of the issues are results of Heroku editing path directories, although, I've scanned the code and see no issues. Current directory (previously working) home/myproject/myproject/mysite settings.py import django_heroku import dj_database_url import dotenv import os.path import django.core.mail # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Load enviroment variables from .env dotenv_file = os.path.join(BASE_DIR, ".env") if os.path.isfile(dotenv_file): dotenv.load_dotenv(dotenv_file) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' 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', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = {} DATABASES['default'] = dj_database_url.config(conn_max_age=600) # Password validation # …