Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How we can verify Email and SMS OTP at same time
I'm implementing 2FA with Twilio. I want to verify email and SMS OTP both at the same time. If I send Email and SMS OTP if the User enters the wrong OTP one of the. The valid otp verifies but the other one is not. how we can achieve this to verify both at the same time. -
Django ckeditor unable to save edited initial values of a form field
I am using a class based create view to show a form to the end user. One of the fields of the form shows an initial value, which would be changed by the end user, before saving the values to the database. The form looks like the below: class R1Form(forms.ModelForm): interview_date = forms.DateField(widget=DateInput()) feedback = forms.CharField(widget=CKEditorWidget()) def __init__(self, *args, **kwargs): super(R1Form, self).__init__(*args, **kwargs) self.initial['feedback'] = template_R1.objects.all().first().template class Meta: model = R1 fields = ['interview_date', 'interviewers', 'feedback', 'comment', 'recommended_level', 'progress'] widgets = {'feedback': CKEditorWidget()} In the above form the field called 'feedback' shows an initial value from the database. The class based, create view looks like below: class R1CreateView(LoginRequiredMixin, UserPassesTestMixin, CreateView): model = R1 form_class = R1Form template_name = "interviews/r1/create.html" # This a quick way to populate fields not present in the model form, but required in the model. def form_valid(self, form): form.instance.candidate_id = self.kwargs['candidate'] return super().form_valid(form) # Required because with HTMX we need to provide a url for post request, and our url also requires additional parameters def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['page'] = self.request.GET.get('page', 1) context['candidate_pk'] = self.kwargs['candidate'] return context def get_success_url(self): return reverse_lazy("cvscreenings-success", kwargs={'candidate': self.kwargs['candidate'], 'message': 'Saved!'}) def test_func(self): return True When the form is shown to … -
How to create custom db model function in Django like `Greatest`
I have a scenario that, i want a greatest value with the field name. I can get greatest value using Greatest db function which django provides. but i am not able to get its field name. for example: emps = Employee.objects.annotate(my_max_value=Greatest('date_time_field_1', 'date_time_field_1')) for e in emps: print(e.my_max_value) here i will get the value using e.my_max_value but i am unable to find out the field name of that value -
== operator not working in if statement in Python Django
Hi Everyone I am creating one function and use row sql query to get data but when use if statement with == operator then expected output is not coming, inside for loop what data if date is today that day of trips 0 but i am getting null value, please help me out. views.py def car_report(request): start_date = request.GET.get('start_date') end_date = request.GET.get('end_date') dates = request.GET.getlist('dates[]') team_id = int(request.GET.get('team_id')) today_date= datetime.today().strftime('%Y-%m-%d') car_report= connection.cursor() car_report.execute(''' SELECT * from table ''', [dates[0],dates[1],dates[2],dates[3],dates[4],dates[5],dates[6],team_id,start_date,end_date]) car_report_data = car_report.fetchall() json_res=[] for row in car_report_data: srow = [x.decode('utf-8') if isinstance(x, bytes) else x for x in row] json_obj=dict(car_number=srow[0],name=srow[1],total_trips=srow[2],status=srow[3],day1_trips=srow[4],day2_trips=srow[5],day3_trips=srow[6],day4_trips=srow[7],day5_trips=srow[8],day6_trips=srow[9],day7_trips=srow[10],total_online_hours=srow[11],total_revenue=srow[12],dead_km=srow[13],yesterday_online_hours=srow[14],yesterday_revenue=srow[15],today_trips=srow[16]) print(json_obj) if dates[2] == today_date: #if statement is not exicuted print(dates[2]) print(today_date) json_obj['day3_trips']=0 json_res.append(json_obj) return JsonResponse(json_res, safe=False) -
Pytorch Model causing 500 server error in Django App
This is My Django project Directory, and in the "bills" app, I am trying to import my YOLOV5 pre-trained custom model (which works fine on its own). So Views.py : def crop(request): model = torch.hub.load('../yolov5-master', 'custom', path='../best.pt', force_reload=True) return render(request, '../templates/results.html') This is causing my app to return a 500 server error when hitting that URL; I know the model is causing it because if I comment out that first line #model = torch.hub.load('../yolov5-master', 'custom', path='../best.pt', force_reload=True) Then the page shows fine. I looked up many articles on how to load a Pytorch model into Django and it seems I am doing it right, can you please help me figure out what's the problem ? -
Django Rest Framework/Djoser sending role information to frontend (Vue)
I am working on a simple site with a login functionality. To handle auth in the backend I am using the Djoser library. I have login functionality working. However now I want to create a site on my frontend which has restricted access based on a users roles. What I want is that if a users is admin/staff then the frontend site has another page in the navbar. So my question is, how should I go about handling this. My first thought is that, when the user is logging in, then the token is sent to the frontend and stored, and then with the token I would also send the users role and store this aswell. However I am not sure how to extend Djoser to do this. Another option would be to simply say that after the user has logged in and received the token and stored it in the frontend, I would make a subsequent request to the backend to get that users information including its role and store that aswell. This of course takes 2 backend calls instead of one as in the first option. To me it seems optimal to use the first option, however I … -
import ra.admin.admin could not be resolved django
I am having issues using the ra framework in django, I am using vs code, python 3.8.10, each time I try to import the ra framework there is a yellow line. what do I do to resolve this -
How to swap a Django ManytoMany relationship
I have a situation where two models have been previously created: class Publisher(models.Model): name = models.CharField(max_length=255) publications = models.ManyToManyField('Publication') class Publication(models.Model): name = models.CharField(max_length=255) and now due to a change in how these models are being used, I need to move the ManyToManyField over to the other model, to hopefully end up with: class Publisher(models.Model): name = models.CharField(max_length=255) class Publication(models.Model): name = models.CharField(max_length=255) publishers = models.ManyToManyField('Publisher') while maintaining the existing relations between the two models. Is this possible? I've tried swapping the relation over but the migration that is generated only removes the field from the old model, which doesn't seem right. How can I preserve the ManyToMany link when I move the field from one Model to the other? -
Notification in django?
I have been developing in django for sometime now, and have developed a neat website having functionality such as writing blogs, posting questions, sharing content etc. However there is still one thing that is missing and i.e. creating notification for users. What I want to do is to inform users in their profiles, whenever somebody comments on their posts, or if they are following a particular post and there is an update on it, then inform the user of that update. I have looked around many applications but I am still very confused about how to do it. In case of using django-notification I seem to have an impression(which can be wrong) that I can use this only to inform the user via email, i.e. I cannot show these notifications in the user profile, just like we have on facebook. Firstly I would like to know if I am wrong, and then I really need some proper tutorial or guidance on how to go about doing it. I know how to register a notification and send it on proper signal but there is no documentation on how to show these notices in a template, if this can be done. Any … -
Creating fake model in djanago rest framework without migrating it for using in swagger
I am trying to implement swagger ui using in Django Rest Framework using drf-spectacular. I don't have any database insatlled yet and in this phase I don't want to implement or create any database or table. I only want to create an API Contract with different Endpoints and showing required and response data types in swagger ui. My question is, that how can I create a model (fake model) without implementing it and without migration? -
Positive Validation Check Django Not Working
I have to create this validation rule when Start= (start_new + start_old) >0 or is positive and End = (end_new + end_old) >0 or is positive then the validation error will raise that" Positive Strat and Positive End are not allowed in the conjunction", But with my below code it is not checking the validation rule and allowing the positive start and positive end values in the conjunction. my code in django form.py for i in range(count): start_new = int(self.data.get(f'applicationruntime_set-{i}-start_new') or 0) start_old = int(self.data.get(f'applicationruntime_set-{i}-start_old') or 0) end_new = int(self.data.get(f'applicationruntime_set-{i}-end_new') or 0) end_old = int(self.data.get(f'applicationruntime_set-{i}-end_old') or 0) if (start_new + start_old) > 0 and (end_new+end_old) > 0: raise ValidationError( f" Positive Start values and Positive End values are not allowed to be used in conjunction") -
custom email verifivcation template
I am using dj rest auth for authentication and i need to override email verification template with my custom html , according to documantion, i added these files to account/email directory: account/email/email_confirmation_signup_subject.txt account/email/email_confirmation_signup_message.txt account/email/email_confirmation_subject.txt account/email/email_confirmation_message.txt account/email/email_confirmation_signup_message.html account/email/email_confirmation_message.html and i put the custom html codes in email_confirmation_message.html file , but still i get the default html template in email , is there any step i am missing? -
Dynamic django select field returns form-invalid
I have form with one select field, when page is loaded I will send ajax request to fetch current user's company categories. Upto this point everything is working as expected, but when I submit the form will return form-invalid. I am not familier with django forms. I will really appreciate if you can figure out what is wrong with my code MODEL class Expense(models.Model): slug = models.SlugField(max_length=80, unique=True) debit = models.DecimalField(decimal_places=2, max_digits=10) date = models.DateTimeField(default=timezone.now) category = models.CharField(max_length=50, choices=()) remark = models.CharField(max_length=50, validators=[MinLengthValidator(3)]) company = models.ForeignKey(Company, on_delete=models.CASCADE) VIEW def expense_types(request, company_id): company = Company.objects.filter(company_id=company_id).first() types = ExpenseType.objects.filter(company=company).all() output = [] for typ in types: data = {} data['category'] = typ.category output.append(data) return JsonResponse({'categories': output}) URL path('<str:company_id>/ExpenseTypes', views.expense_types, name='get-expense-types') TEMPLATE <form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %} {{ form|as_crispy_errors }} <div class="row"> <div class="col-md-6 col-sm-6"> {{ form.date|as_crispy_field }} </div> <div class="col-md-6 col-sm-6"> {{ form.debit|as_crispy_field }} </div> </div> <div class="row"> <div class="col-md-6 col-sm-6"> {{ form.category|as_crispy_field }} <input type="hidden" id="company_id", value="{{ user.company.company_id }}"> </div> <div class="col-md-6 col-sm-6"> {{ form.remark|as_crispy_field }} </div> </div> <div class="form-group"> <button class="btn btn-outline-warning btn-block" type="submit">Save</button> </div> </form> <script type="text/javascript"> let category = document.getElementById('id_category') let company_id = document.getElementById('company_id').value fetch('/' + company_id + '/ExpenseTypes').then(function(response){ response.json().then(function (data){ let optionHTML = '' for … -
Django serializer.save() gives back a HTTP 400 Bad Request
I have the following straightforward setup: a folder order with a models.py file, from django.contrib.auth.models import User from django.db import models from product.models import Product class Order(models.Model): user = models.ForeignKey(User, related_name='orders', on_delete=models.CASCADE) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.CharField(max_length=100) address = models.CharField(max_length=100) zipcode = models.CharField(max_length=100) place = models.CharField(max_length=100) phone = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) paid_amount = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) stripe_token = models.CharField(max_length=100) class Meta: ordering = ['-created_at',] def __str__(self): return self.first_name class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='items', on_delete=models.CASCADE) price = models.DecimalField(max_digits=8, decimal_places=2) quantity = models.IntegerField(default=1) def __str__(self): return '%s' % self.id a serializers.py file from rest_framework import serializers from .models import Order, OrderItem class OrderItemSerializer(serializers.ModelSerializer): class Meta: model = OrderItem fields = [ "price", "product", "quantity", ] class OrderSerializer(serializers.ModelSerializer): items = OrderItemSerializer(many=True) class Meta: model = Order fields = [ "id", "first_name", "last_name", "email", "address", "zipcode", "place", "phone", "stripe_token", "items", ] def create(self, validated_data): items_data = validated_data.pop('items') order = Order.objects.create(**validated_data) for item_data in items_data: OrderItem.objects.create(order=order, **item_data) return order and finally, a views.py file import stripe from django.conf import settings # get secret key from rest_framework import status, authentication, permissions from rest_framework.decorators import api_view, authentication_classes, permission_classes from rest_framework.response import Response from .serializers import … -
Django chained dropdowns with ajax
I hope you are all doing well, I have implemented a Dependent / Chained Dropdown List for dropdown and it was working properly, but while I add the third one, it is not working well until reload the page. this is my try : here is the HTML code and the ajax script: <form method="post" id="studentForm" data-branches-url="{% url 'ajax_load_branches' %}" novalidate> {% csrf_token %} <table> {{ form.as_table }} </table> <button type="submit">Save</button> <a href="{% url 'student_changelist' %}">NevermiNnd</a> </form> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $("#id_college").change(function () { var url = $("#studentForm").attr("data-branches-url"); var collegeId = $(this).val(); $.ajax({ url: url, data: { 'college': collegeId }, success: function (data) { $("#id_branch").html(data); } }); }); $("#id_branch").change(function () { var url = $("#studentForm").attr("data-reds-url"); var branchId = $(this).val(); $.ajax({ url: url, data: { 'branch': branchId }, success: function (data) { $("#id_red").html(data); } }); }); </script> form.py class StudentForm(forms.ModelForm): class Meta: model = Student fields = ('name', 'birthdate', 'college','branch','red') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['branch'].queryset = Branch.objects.none() self.fields['red'].queryset = Red.objects.none() if 'college' in self.data: try: college_id = int(self.data.get('college')) self.fields['branch'].queryset = Branch.objects.filter(college_id=college_id).order_by('name') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset if self.instance.pk: self.fields['branch'].queryset = self.instance.college.branch_set.order_by('name') if 'branch'in self.data: try: branch_id = int(self.data.get('branch')) … -
Serialize pandas dataframe consists Nan fields before sending as a response
I have a dataframe that has Nan fields in it. I want to send this dataframe as a response. Because it has Nan fields I get this error, ValueError: Out of range float values are not JSON compliant I don't want to drop the fields or fill them with a character or etc. and the default response structure is ideal for my application. Here is my views.py ... forecast = forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']] forecast['actual_value'] = df['y'] # <- Nan fields are added here forecast.rename( columns={ 'ds': 'date', 'yhat': 'predictions', 'yhat_lower': 'lower_bound', 'yhat_upper': 'higher_bound' }, inplace=True ) context = { 'detail': forecast } return Response(context) Dataframe, date predictions lower_bound higher_bound actual_value 0 2022-07-23 06:31:41.362011 3.832143 -3.256209 10.358063 1.0 1 2022-07-23 06:31:50.437211 4.169004 -2.903518 10.566005 7.0 2 2022-07-28 14:20:05.000000 12.085815 5.267806 18.270929 20.0 ... 16 2022-08-09 15:07:23.000000 105.655997 99.017424 112.419991 NaN 17 2022-08-10 15:07:23.000000 115.347283 108.526287 122.152684 NaN Hoping to find a way to send dataframe as a response. -
How To Resolve MVT with Postgrse SQL Error?
just giving black screen error whenever try to connect or perform. Tried to map it again but not working. Installed Properly as well as showing reflection in terminal. -
Django Model Meta options - custom permissions no effect in production
I added custom permissions for Django's import-export library in the Model Meta options. Example from the documentation: class Task(models.Model): ... class Meta: permissions = [ ("change_task_status", "Can change the status of tasks"), ("close_task", "Can remove a task by setting its status as closed"), ] This works fine on the local server but in production there seems to be no effect when the permissions are applied to a user. The custom permissions can still be found in the permissions-list of the admin page for users and groups but when applied the user still can't see the import/export buttons. The according migration files ran fine when deploying. We use Django 3.1.2 and django-import-export 2.5.0. Has anyone ever had this problem before? Where are the Model meta options actually stored after the migration? Thanks in advance! -
DjangoRestFramework: Not able to set permissions for custom user model
I've created a custom user model in my project using an abstract base user but when I'm setting permissions for my User view it's giving me a field error. I wanted to set permission for Admin and Non-Admin users: (a) Admin user: It can access any user (View/edit). (b) Non-Admin user: It can access its own object (view/edit). so something like permission_classes = [IsUserOrIsAdmin] I've shared my corresponding model.py, serializers.py, view.py, permissions.py, and traceback for the same. I'm working on these 2 endpoints: path('customer/', UserListCreateAPIView.as_view()), path('customer_info/<int:pk>/', UserRetrtieveUpdateDestroyAPIView.as_view()), ***models.py*** import email from pyexpat import model from django.db import models from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser) GENDER_CHOICES = ( (0, 'male'), (1, 'female'), (2, 'not specified'),) class UserManager(BaseUserManager): def create_user(self, email, name,contact_number,gender,address,state,city,country,pincode,dob ,password=None, password2=None): """ Creates and saves a User with the given email, name, and password. """ if not email: raise ValueError('User must have an email address') user = self.model( email=self.normalize_email(email), name=name, contact_number=contact_number, gender=gender, address=address, state=state, city=city, country=country, pincode=pincode, dob=dob, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, name,contact_number,gender,address,state,city,country,pincode,dob , password=None): """ Creates and saves a superuser with the given email, name, and password. """ user = self.create_user( email, … -
django rest framework upload image to related model using generic.createAPIView
I am scheduling a medical camp at some destination. After reaching the destination i want to upload picture of that destination of mapped destination. I Created two model for that One is SiteMap class SiteMap(models.Model): MpId = models.IntegerField(verbose_name='MPID') VisitingDate = models.DateField(default=timezone.now,verbose_name='Date') Vehical = models.ForeignKey(VehicalMaster,on_delete=models.CASCADE,verbose_name='Vehical') Doctor = models.ForeignKey(User,on_delete=models.CASCADE,verbose_name='Doctor') District = models.ForeignKey(District,on_delete=models.CASCADE,verbose_name='District') Block = models.ForeignKey(Block,on_delete=models.CASCADE,verbose_name='Block') Panchayat = models.CharField(max_length=120,verbose_name="Panchayat") Village = models.CharField(max_length=120,verbose_name='Village') updated = models.DateTimeField(auto_now=True) And secod one is SiteMapImage class SiteMapImage(models.Model): MPID = models.ForeignKey(SiteMap,on_delete=models.CASCADE,verbose_name='MPID') SiteImage = models.ImageField(default='default.png',upload_to='sitemap/%Y/%m/%d') Location = models.CharField(max_length=200,verbose_name='Location',null=True,blank=True) Latitude = models.CharField(max_length=120,verbose_name='Latitude',null=True,blank=True) Longitue = models.CharField(max_length=120,verbose_name='Longitude',null=True,blank=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.MPID}" def save(self): super().save() siteimg = Image.open(self.SiteImage.path) if siteimg.height>300 or siteimg.width>300: output_size = (300,300) siteimg.thumbnail(output_size) siteimg.save(self.SiteImage.path) I have created a serializer class for this. Here is the code. class SiteMapImageSerializer(serializers.ModelSerializer): class Meta: model = SiteMapImage fields = ['MPID','Location','Latitude','Longitue','SiteImage'] and this is my view.py class SiteMapImageCreateView(generics.CreateAPIView): lookup_field = 'SiteMap.pk' serializer_class = SiteMapImageSerializer def get_queryset(self): return SiteMapImage.objects.all() I don't know what wrong i did. but not working in broweser too. I upload the error image tooo. -
Highlighting current url not working with request resolver
I have the following urls from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('landing', views.landing, name='landing'), path('json', views.json, name='json'), path('bootstrap', views.bootstrap, name='bootstrap'), path('page', views.page, name='page'), ] I am using twitter bootstrap 5 and i want to highlight home when a user visits the landing page and append active when the current url matches <li class="nav-item"> <a href="{% url '' %}" class="nav-link {% if request.resolver_match.view_name == '' %}active{% endif %}">Home</a> </li> <li class="nav-item"> <a href="{% url 'page' %}" class="nav-link {% if request.resolver_match.view_name == 'page' %}active{% endif %}">Page</a> </li> I get this error django.urls.exceptions.NoReverseMatch: Reverse for '' not found. '' is not a valid view function or pattern name. Even when i replace the blank '' with 'landing' the active class is not appended.How can i correct this? -
Erros: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
new to django django version : Django==2.2 getting below error : Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS while running below commands: python3.7 manage.py collectstatic python3.7 manage.py shell python3.7 manage.py runserver below is what my INSTALLED_APPS look like INSTALLED_APPS = ( 'actions.apps.MyAppConfig', 'common.apps.MyAppConfig', 'hotels.apps.MyAppConfig', 'extranet.apps.MyAppConfig', 'communication.apps.MyAppConfig', 'bulk_uploader.apps.MyAppConfig', 'registration.apps.MyAppConfig', 'channel_manager.apps.MyAppConfig', 'reports.apps.MyAppConfig', 'mobile.apps.MyAppConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'admin_shortcuts', 'guardian', 'actstream', 'rest_framework', 'django_filters', 'rest_framework.authtoken', 'oauth2app', 'ckeditor', 'stats', 'django_celery_beat', ) any suggestion? -
Calculation of input value and store it into database django
I want per unit price value according to input value and save it on database, I don't know how to do this task kindly help me plz model.py class Celldetail(models.Model): CellInvoiceNo = models.IntegerField(null=True, blank=True) Cell_Type = models.CharField(max_length=200, null=True) Cell_qty = models.DecimalField(default=0) Cell_price = models.DecimalField(default=0) Cell_PUP = models.FloatField() views.py def add_inventory_view(request): form = CellForm(request.POST or None) if form.is_valid(): form.save() context = { 'form': form, } return render(request, "addinventory.html", context) -
how to reload page in django using js2py?
i run script every 15 mins to update data on my website but i want to reload ppage in browser after update automatically i tried to put window.location.reload(true) using js2py and script looks like this: import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') import django django.setup() from django.core.management import call_command import time import js2py js = """ window.location.reload(true); """ def reload(): context = js2py.EvalJs() context.execute(js) while True: call_command("feed_update") reload() time.sleep(900) and i get error: raise MakeError('TypeError', js2py.internals.simplex.JsException: TypeError: Undefined and null dont have properties (tried getting property 'reload') -
Django blog page, admin page stopped working
I try to code a blog with Django and it worked pretty well until I couldn't open the admin page anymore: 127.0.0.1:8000/admin/. I created a superuser I could login to the admin page but then I changed something else but I can't say what. The blog with the database and my personal was working except the admin page. Do you have any idea why that happened? Appreciate any help. The following image shows the failure message: Here is my code: settings.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'xxx' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'ckeditor', 'ckeditor_uploader', 'taggit', 'django.contrib.sites', 'django.contrib.sitemaps', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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 = 'thomkell.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [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 = 'thomkell.wsgi.application' # Database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': …