Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - TIME_ZONE and timezone.now()
I've the following settings:- TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_TZ = True Also, I've set auto_now = True in my DateTimeField's. However, the datetime that gets saved in the column in of UTC (ie -5:30 hours). I have set my system date as per the Asia/Kolkata timezone. Also, >>> from django.utils import timezone >>> from datetime import datetime >>> >>> datetime.now() datetime.datetime(2019, 7, 13, 17, 40, 1, 505516) # this is right >>> timezone.now() datetime.datetime(2019, 7, 13, 12, 10, 6, 496772, tzinfo=<UTC>) # this is not what I expect. Why is there a discrepency in timezone.now() even when TIME_ZONE is rightly set?? -
How to limit the number of forgot password send reset email attempts?
I'm using the Django in built forgot password reset form and views. I want to limit the number of reset password email attempts. By default Django allows you to send many reset password email without any limit. -
How to get all ancestors of a Django object when ForeignKey is not self-referencing?
I have a model Person and another model Relation. Before creating a new relation I want to check if this relation is possible or not. This post and some other similar posts provides a solution but for self-referencing models, my model is not self referencing. Django self-recursive foreignkey filter query for all childs class Person(models.Model): identifier = IntegerField(null=True) title = CharField(max_length=100, null=True) def get_all_parent_ids(self): # I want to get all the ancestors of this person # but this method only gets immediate parents right now return [parent.parent.id for parent in self.parenting.all()] def get_all_children_ids(self): # I want to get all the descendants of this person # but this method only gets immediate children right now return [child.children.id for child in self.baby_sitting.all()] class Relation(models.Model): name = CharField(max_length=50, null=True) parent = ForeignKey(Person, on_delete=models.PROTECT, related_name="parenting") children = ForeignKey(Person, on_delete=models.PROTECT, related_name="baby_sitting") class Meta: unique_together = ('parent', 'children') def is_relation_possible(new_parent_id, new_children_id): new_parent_person = Person.objects.get(pk=new_parent_id) all_parents = new_parent_person.get_all_parent_ids() if new_children_id in all_parents: return False else: return True For example: Existing relaions - A to B - B to C - C to D - D to E I want is_relation_possible(E, A) to return False, as E has an ancestor A. Currently it only check immediate parents and … -
Django FactoryBoy TestCase handling nested object creation
I am trying to write TestCase with django factory and this lill bit advance testcase writing.. This is my models.py below: class Author(models.Model): name = models.CharField(max_length=25) def __str__(self): return self.name class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='author') title = models.CharField(max_length=200) body = models.TextField() def __str__ (self): return self.title and this is my tests.py below from django.test import TestCase from library.models import Author, Book import factory # Create factory for model class AuthorFactory(factory.django.DjangoModelFactory): class Meta: model = Author name = 'author name' class BookFactory(factory.django.DjangoModelFactory): class Meta: model = Book author = factory.SubFactory(AuthorFactory) title = 'i am title' body = 'i am body' # Start TestCase here class TestSingleBook(TestCase): def setUp(self): self.author = AuthorFactory.create_batch( 10, name='Jhon Doe' ) self.book = BookFactory.create_batch( author=self.author ) def test_single_book_get(self): # compare here above code, my testcase class is class TestSingleBook(TestCase): i hope you noticed it.. I want to create 10 Author and create 10 book with those 10 Author, and then i will compare it in assertEqual if i create multiple book with single author, i can craft the test easily but i dont want it... My Problem is Nested/Multiple... Create multiple author and then create multiple book with those author... is there anyone who solved … -
URL param in POST
Recently I was task for a small project with one of the following REST API specification METHOD ROUTE POST/PUT /plays/{:uuid} My code class Play(models.Model): id = models.Charfield(primary_key=True,default=None, mx_length=255) allOtherfielshere...... I am using ModelViewSet here from rest_framwork, my question is, is it possible to get the url string, which is the {:uuid} part and pass as the value of id in the model? Also how to set the url? My url for plays looks like this app_name = 'plays' urlpatterns =[ path('', include(router.urls) ] This works will if the data comes from form body or json object, but with url params and form together, is it possible? -
Django(v. 1.11.3 ) HttpResponse not returning the specified reason phrase
In one of my views, called via an XMLHttpRequest, I am trying to return an HttpResponse object with a status code and a reason phrase. When I make a request to that specific view, the response that I get has the specified status code but the phrase that I keep getting is "error" for when returning a 40x response type, an empty string when returning a 20x...instead of the phrase that I specify. from django.http import HttpResponse def auth_validate(request): return HttpResponse(status=401, reason="Login failed") What am I missing or doing wrong? -
Django and CORS policy with multiple allowed hosts
I have a small Django project running on a ubuntu server with NGINX and gunicorn. Everything works great when users visit www.example.com, However, when a user visits example.com instead of www.example.com, this is where it falls apart. I am using some javascript with the fetch command, to get data from my API (Django REST) and it returns: Access to fetch at 'https://www.example.com/builds/apidata/4' from origin 'https://example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. The easiest solution I have found is to just remove example.com from my ALLOWED_HOSTS in my settings.py file, but then when users forget www. they will be greeted with a 404 error. The CORS error message also states I can change the request mode, but I don't know the security implications of this.. I also tried to use redirection on my domain settings from example.com to www.example.com, but this doesn't seem work either. Any suggestions would be appreciated! -
How to get red of 'Apps aren't loaded yet' in django whenever I run the code?
I made a search bar. The name which I will type in it should give me its name, email detail etc but whenever I run the code it is giving me following error. django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Here is my main url pages and app url page. main url from django.contrib import admin from django.urls import path, include from firstapp.views import * urlpatterns = [ path('admin/', admin.site.urls), path('', include('firstapp.urls')), path('', search, name='search') app url from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('', views.search, name='search') ] -
How to pass clickable image from one page to another html page in Django
I have a clickable image on my menu.html page which when clicked redirects to mycart.html. I want this same image on my mycart template **Below is my code for menu.html:** {%for count in item%} <div class="col-md-6 col-lg-4 menu-wrap"> <div class="heading-menu text-center ftco-animate"> <h3>{{count.supper}}</h3> </div> <div class="menus d-flex ftco-animate"> <a href="{% url 'mycart' %}"> <div style="background-image: url({{count.pic.url}});"></div> </a> <div class="text"> -
how to add custom method in django rest framework
i can handle the crud api of the model easily thanks to django rest frame work but what if i want to add the custom api to the booking model for example here is my code below : here is my serializer : from rest_framework import serializers from .models import Booking class BookingSerializer(serializers.ModelSerializer): class Meta: model = Booking fields =( 'user_id', 'computed_net_price', 'final_net_price', 'payable_price', 'booking_status', 'booking_status', 'guest_name', 'guest_last_name', 'guest_cellphone', 'guest_cellphone', 'guest_cellphone', 'operator_id', 'is_removed', ) and my view : from rest_framework import viewsets from .models import Booking from booking.serializers import BookingSerializer # Create your views here. class BookingView(viewsets.ModelViewSet): queryset = Booking.objects.all() serializer_class = BookingSerializer and my urls : from django.urls import path,include from . import views from rest_framework import routers router = routers.DefaultRouter() router.register('Booking',views.BookingView) router.register('BookingApi',views.BookingView) urlpatterns = [ #path('',include('facility.urls')) path('',include(router.urls)) ] so if i want to add the new api names bookingapi for example should i duplicate all thing in the same files??? or make new files the same name in the model or any thing else how can i achive it -
How can i update a page without reloading with Ajax and Django Rest Framework?
In my Django project, i'm trying to create a page where some data is uploaded in real time, without reloading the whole page. That data is retrieved from a database, so i created an API endpoint with Django Rest Framework, the problem is that i don't know how to go from here. I already know that, to update the page, i'll need to use Ajax. But i don't know how to create the Ajax part. I think that i need to add a POST request in my template, but that's all i know for now. Can someone give me some direction on where to go from here? Any advice is appreciated Basically the Ajax request should call the endpoint, which is http://127.0.0.1:8000/tst/, and update the data every X (something between 1 and 5 seconds). serializers.py class tstSerializer(serializers.ModelSerializer): class Meta: model = tst fields = ('ticker', 'Price', ) def create(self, validated_data): return tst.objects.create(**validated_data) views.py class tstList(generics.ListCreateAPIView): queryset = tst.objects.using('screener').all() serializer_class = tstSerializer class tstDetail(generics.RetrieveUpdateDestroyAPIView): queryset = tst.objects.using('screener').all() serializer_class = tstSerializer template.html <h3>Here will be a table with the data uploaded in real time..</h3> -
count and grouped by
I would like to count the number of fields (car_number) returned grouped by country. class CarViewSet(viewsets.ModelViewSet): queryset = car.objects.only('car_country').select_related('car_country') serializer_class = CarSerializer class CountrySerializer(serializers.ModelSerializer): class Meta: model = country fields = ('country_name',) class CarSerializer(serializers.ModelSerializer): car_country = CountrySerializer() class Meta: model = car fields = ('car_number','car_country',) The result I got now is as follows: [ { "car_number": "45678", "car_country": { "country_name": "Europe/UK" } }, { "car_number": "3333333", "car_country": { "country_name": "Europe / Netherlands" } }, { "car_number": "11111111111", "car_country": { "country_name": "Europe/UK" } } ] -
Django Rest Framework - Bad request
I'm trying to call an api endpoint on my Django project from my frontend. The endpoint is at the url /tst/. I need to retrieve data from that endpoint, in order to populate my page with that data. I'm using an ajax request for this, but i keep getting the error 400 - BAD REQUEST, but i don't know why this happens, since the api endpoint is at the right URL. function doPoll(){ $.post('http://localhost:8000/tst/', function(data) { console.log(data[0]); $('#data').text( data[0].data); setTimeout(doPoll, 10); }); } My endpoint's view: class tstList(generics.ListCreateAPIView): queryset = tst.objects.using('screener').all() serializer_class = tstSerializer -
Django: delete/update model only if respect the conditions
I am new in python/django and i need help for this situation: WeeklyCheck = start_Date >>> end_date - Week Active User Check the attendance in one of date in Week because that week is Active. User can delete/update that check that he made, but only if the week is Active. Then: Week = start_Date -> end_date - Week Not Active User now can not delete/update that check the attendance tha he made because the week is Not Active. models.py class WeeklyCheck(models.Model): start_date = models.DateField(blank=False, null=True, verbose_name='Start date') end_date = models.DateField(blank=False, null=True, verbose_name='End Date') active = models.BooleanField(default=True, verbose_name='Active?') def __str__(self): return '{} / {} to {} - {}'.format(self.department, self.start_date, self.end_date, self.active) class Attendance(models.Model): user = models.ForeignKey(User, related_name='attendance_user', on_delete=models.CASCADE) date = models.DateField(blank=False, null=True, verbose_name='Date') check = models.BooleanField(default=True, verbose_name='Check') def __str__(self): return '{} / {} / {}'.format(self.user, self.date, self.check) forms.py class WeeklyCheckForm(forms.ModelForm): class Meta: model = WeeklyCheck fields = [ 'start_date', 'end_date', 'enable', ] class AttendanceForm(forms.ModelForm): class Meta: model = Attendance fields = [ 'user', 'date', 'check', ] views.py def check_edit(request, pk=None, pkk=None): weeks = WeeklyCkeck.objects.all() user = get_object_or_404(User, id=pk) check = get_object_or_404(Attendance, id=pkk) form = AttendanceForm(request.POST or None, request.FILES or None, instance=check) if form.is_valid(): instance = form.save(commit=False) instance.save() return HttpResponseRedirect(reverse("check_list", kwargs={'pk': pk})) … -
AttributeError: 'HttpResponse' object has no attribute 'rendered_content'
i want to attach a pdf in mail (django python)and the function i have call on pdf_response variable is converting my html into pdf from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart msg = MIMEMultipart('related') attachment = msg.attach(pdf_response.rendered_content) attachment['Content-Disposition'] = 'attachment; filename="xyz.pdf"' msg.attach(attachment) -
How to connect plaid to stripe using django
I was using stripe in django but i am new for plaid . Now i want to connect plaid with my django app and than pay with plaid + stripe. I refer below document but i cant understand how to work document link: https://plaid.com/docs/stripe/ https://stripe.com/docs/ach#using-plaid I was test below code but than next what to do i don't know <button id='linkButton'>Open Plaid Link</button> <script src="https://cdn.plaid.com/link/v2/stable/link-initialize.js"></script> <script> var linkHandler = Plaid.create({ env: 'sandbox', clientName: 'Stripe/Plaid Test', key: '1bde1c39022bbcecaccde8cc92182d', product: ['auth'], selectAccount: true, onSuccess: function(public_token, metadata) { // Send the public_token and account ID to your app server. console.log('public_token: ' + public_token); console.log('account ID: ' + metadata.account_id); }, onExit: function(err, metadata) { // The user exited the Link flow. if (err != null) { // The user encountered a Plaid API error prior to exiting. } }, }); // Trigger the Link UI document.getElementById('linkButton').onclick = function() { linkHandler.open(); }; </script> -
I am newbie in programming. Can you please help me to dispatch this url in python?
I want to dispatch a url of type: /algorithms/algorithm_name/topic/ I am working on django. This is what I tried: url(r'^(?P<topic_name>[a-zA-Z a-zA-Z a-zA-Z]+)/$',views.topic,name='topic'), How to write the regex pattern for my url type? -
Best approach to building a student marks tracking system
Am trying to build a system in django which will allow me to track marks of students from various semesters in various subjects. I have sucessfully built the registration system and both Students and Teachers can register and login to the system. I want to be able to allow the teachers to enter marks students have secured in different examinations in different semesters. I want to have an easy and user friendly way that Teachers can enter marks and also allow students to be able to view their marks in the various tests and various papers over the semesters. In effect allowing them to monitor their progress in the courses they attend. I would appreciate any inputs on how I might approach this problem and implement it with django. Thank you all for your time -
Pip installation of pygdal with osx gdal binding fails
I'm trying to run a geoDjango project on OSX Mojave (10.14.5). Therefore I've installed the dependencies as suggested on the Django docs from kyngchaos (tried brew packages as well) Created my virtualenv which shows New python executable in /Users/ts/.virtualenvs/project_upstream/bin/python2.7 Also creating executable in /Users/ts/.virtualenvs/project_upstream/bin/python checked gdal with $ gdal-config --version 2.4.1 and tried to install pygdal with: pip install pygdal==2.4.1.* which fails with ERROR: Complete output from command /Users/ts/.virtualenvs/project_upstream/bin/python2.7 -u -c 'import setuptools, tokenize;__file__='"'"'/private/var/folders/j6/wr2vpjzn3698tdsng2j56d7m0000gn/T/pip-install-qTnsBS/pygdal/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/j6/wr2vpjzn3698tdsng2j56d7m0000gn/T/pip-record-vlffrN/install-record.txt --single-version-externally-managed --compile --install-headers /Users/ts/.virtualenvs/project_upstream/bin/../include/site/python2.7/pygdal: ERROR: running install running build running build_py creating build creating build/lib.macosx-10.14-x86_64-2.7 creating build/lib.macosx-10.14-x86_64-2.7/osgeo copying osgeo/gnm.py -> build/lib.macosx-10.14-x86_64-2.7/osgeo copying osgeo/__init__.py -> build/lib.macosx-10.14-x86_64-2.7/osgeo copying osgeo/gdalnumeric.py -> build/lib.macosx-10.14-x86_64-2.7/osgeo copying osgeo/osr.py -> build/lib.macosx-10.14-x86_64-2.7/osgeo copying osgeo/gdal.py -> build/lib.macosx-10.14-x86_64-2.7/osgeo copying osgeo/ogr.py -> build/lib.macosx-10.14-x86_64-2.7/osgeo copying osgeo/gdal_array.py -> build/lib.macosx-10.14-x86_64-2.7/osgeo copying osgeo/gdalconst.py -> build/lib.macosx-10.14-x86_64-2.7/osgeo running build_ext clang -fno-strict-aliasing -fno-common -dynamic -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I/Users/ts/.virtualenvs/project_upstream/lib/python2.7/site-packages/numpy/core/include -I/Library/Frameworks/GDAL.framework/Versions/2.4/include/gdal -I/Library/Frameworks/GDAL.framework/Versions/2.4/include -c gdal_python_cxx11_test.cpp -o gdal_python_cxx11_test.o clang -fno-strict-aliasing -fno-common -dynamic -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I/Users/ts/.virtualenvs/project_upstream/lib/python2.7/site-packages/numpy/core/include -I/Library/Frameworks/GDAL.framework/Versions/2.4/include/gdal -I/Library/Frameworks/GDAL.framework/Versions/2.4/include -c gdal_python_cxx11_test.cpp -o gdal_python_cxx11_test.o -std=c++11 building 'osgeo._gdal' extension creating build/temp.macosx-10.14-x86_64-2.7 creating build/temp.macosx-10.14-x86_64-2.7/extensions clang -fno-strict-aliasing -fno-common -dynamic -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/usr/local/Cellar/python@2/2.7.16/Frameworks/Python.framework/Versions/2.7/include/python2.7 … -
how to use django-ratelimit for graphene resolve
We cannot use django-ratelimit directly for graphql resolve method. Because the default decorator is get request from the first argument. -
Pass Django context to Ajax
I need to pass some data from Django to Ajax so the page will refresh every second. I've seen similar questions, for example this one, but it didn't helped me. The code on the Django side is following: @register.inclusion_tag('core/controller_data.html', name='controller_data') def controller_data(): current_controller_data = poll_controller() data = {'data': current_controller_data} return JsonResponse(data) In the template I have setInterval(function () { $.ajax({ url: "/", type: 'GET', data: {'check': true}, success: function (data) { console.log(data); } }); }, 1000); But instead of Django context, the html code of the template is being rendered in the console. Can you please help me? -
Saving Multiple Images in Form Wizard Django and ManyToMany Fields not Working
I am working on a project in Django that I have to use a Form Wizard. Part of the requirement is to save multiple images in one of the form steps, and to save a many to many field, which are not working as expected. Let me first share my code before explaining the problem. models.py from django.db import models from django.contrib.auth.models import User from location_field.models.plain import PlainLocationField from PIL import Image from slugify import slugify from django.utils.translation import gettext as _ from django.core.validators import MaxValueValidator, MinValueValidator from listing_admin_data.models import (Service, SubscriptionType, PropertySubCategory, PropertyFeatures, VehicleModel, VehicleBodyType, VehicleFuelType, VehicleColour, VehicleFeatures, BusinessAmenities, Currency, EventsType ) import datetime from django_google_maps.fields import AddressField, GeoLocationField def current_year(): return datetime.date.today().year def max_value_current_year(value): return MaxValueValidator(current_year())(value) class Listing(models.Model): listing_type_choices = [('P', 'Property'), ('V', 'Vehicle'), ('B', 'Business/Service'), ('E', 'Events')] listing_title = models.CharField(max_length=255) listing_type = models.CharField(choices=listing_type_choices, max_length=1, default='P') status = models.BooleanField(default=False) featured = models.BooleanField(default=False) city = models.CharField(max_length=255, blank=True) location = PlainLocationField(based_fields=['city'], zoom=7, blank=True) address = AddressField(max_length=100) geolocation = GeoLocationField(blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) expires_on = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE, editable=False, null=True, blank=True ) listing_owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='list_owner' ) def __str__(self): return self.listing_title class Meta: ordering = ['-created_at'] def get_image_filename(instance, filename): title = instance.listing.listing_title slug = slugify(title) … -
"how to fix "No module named 'core' in django"
"""ajax_pro1 URL Configuration The urlpatterns list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.conf.urls import url from core import views enter code here urlpatterns = [ url(enter code herer'^signup/$', views.SignUpView.as_view(), name='signup'), ] -
Django on Heroku: ModuleNotFoundError: No module named 'app_name'
I've been having some trouble getting my Django app with the django rest framework to deploy without errors to heroku. The strange thing is, there would be no issues in pushing and deploying to Heroku but would crash after deployment. Here is my file structure: Include/ man/ Procfile/ requirements.txt runtime.txt Scripts/ tcl/ webadvisorapi │ manage.py ├───src │ │ admin.py │ │ apps.py │ │ models.py │ │ serializers.py │ │ tests.py │ │ urls.py │ │ views.py │ │ __init__.py │ │ │ ├───management │ │ │ __init__.py │ │ │ │ │ └───commands │ │ runrequest.py │ │ __init__.py │ │ │ ├───scripts │ request.py │ __init__.py │ ├───static │ .keep │ ├───staticfiles └───webadvisorapi │ settings.py │ urls.py │ wsgi.py │ __init__.py │ ├───static │ .keep I have already ran this on my own machine and it worked just fine. Interestingly, my app could not be pushed and deployed to Heroku when I use any other path other than src.apps.SrcConfig in INSTALLED_APPS as it gives me the same ModuleNotFoundError. Besides that, I did get a successful deployment but the app crashed. I even cloned my project from heroku and ran my project locally and there was no issue. Here … -
Django formset: file upload does not work
I am using Django to build a help desk and I want to allow the client to upload multiple files when they submit a ticket. I am trying to do this by using a formset. I have found many questions related to a similar problem, but I still have not been able to get my form working. I will appreciate a pointer in the right direction. I have posted the relevant code below: # models.py class Ticket(models.Model): PRIORITY_CHOICES = ( (1, 'Critical'), (2, 'High'), (3, 'Normal'), (4, 'Low'), (5, 'Very Low'), ) STATUS_CHOICES = ( (1, 'Open'), (2, 'Reopened'), (3, 'Resolved'), (4, 'Closed'), (5, 'Duplicate'), ) ticket_number = models.CharField(max_length=50, blank=True, null=True, unique=True) client = models.ForeignKey(settings.AUTH_USER_MODEL, editable=True, on_delete=models.CASCADE, related_name="tickets") title = models.CharField("Summary", max_length=200, help_text='Provide a brief description of your request.') description = models.TextField(blank=True, help_text='Provide as much detail as possible to help us resolve this ticket as quickly as possible.') due_date = models.DateField(blank=True, null=True) assigned_to = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="assigned", blank=True, null=True, on_delete=models.CASCADE) priority = models.IntegerField(choices=PRIORITY_CHOICES, editable=True, default=3, help_text='Please select a priority carefully. If unsure, leave it as "Normal".', blank=True, null=True) status = models.IntegerField(choices=STATUS_CHOICES, editable=True, default=1, blank=True, null=True) closing_date = models.DateField(blank=True, null=True) closing_notes = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) upload = models.FileField(upload_to='uploads/%Y/%m/%d/', …