Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can i implement django oscar "categories" functionality(Parent, childs) in the Django oscar RESTFUL API?
In the oscar dashboard, I can make any root category, I can make children under a category. This functionality I am able to explore in the oscar Restful API. But I want to inherit the dashboard functionality, where we can make any category relative to another category. for example- I have 2 categories. 1) cat 1 a)subcat1 2)cat 2 now if I have to make subcat1 as a child of cat2 I can easily select from the dropdown and set 'subcat1' to cat2, in the oscar dashboard. But how can I do the same using Django oscar restful API? Please let me know. I have checked and found out that "category" model uses the Materialized Path trees, to achieve this functionality, how can I use this to achieve the treebeard functionality for adding the root nodes, adding children, and updating the categories under different categories etc? this is the request data I receive from the client side. { "id": 104, "url": "http://localhost:8000/api/admin/categories/104/", "breadcrumbs": "Cat1 > subcat1", "name": "subcat1", "description": "My new one test Desc", "slug": "subcat1", "parent": "Cat1", "children": "http://localhost:8000/api/admin/categories/Cat1/subcat1/", #here parent slug will be the name of parent category this category belongs to, if it is a parent category, … -
Django: Best way to extend auth_views.LoginView to do an extra check before allowing login to pass, only for login view
I've been trying to figure out the best way to add a single if statement to the baked in contrib.auth.LoginView from Django, to check if the login process should continue. I have in urls.py: from django.contrib.auth import views as auth_views urlpatterns = [ ... url(r'^login/$', auth_views.LoginView.as_view(), name='account_login'), ... ] My task at this point is to check whether a user can log in, by checking their license, using a function that receives a License model instance: def check_license(lic_obj): file_contents = lic_obj.decrypt_license() expiry_date = file_contents['expiry_date'] expiry_date = dateutil.parser.parse(expiry_date) time_now = utc.localize(datetime.datetime.utcnow()) if expiry_date < time_now: users = User.objects.all() for user in users: user.remove_all_sessions() # If license is invalid, redirect to License page return HttpResponseRedirect(reverse('get_license')) # Otherwise, keep going with login, not sure how to go about this either, # depends on how extending LoginView works pass For clarity, a license is just an encrypted bit of JSON with some license related properties, one of which is the license's expiration date. That whole part of the code works, I'm just not sure how to have that check_license() function be run on login, before returning whether the login is successful or not. I was toying with adding a custom middleware class, but that … -
request.user.id is null in ModelViewSet
getInstructor is my repository method, which gets instructor related with user id. @action(methods=['get'], detail=False) def instructor_detail(self, request): response_data = {} instructor = InstructorRepository.getInstructor(request.user.id) response_data["data"] = {"user_id": request.user.id, "detail": instructor.get("detail")} When I test that method with an id, it works. The problem is, request.user.id is always null, even there's no login problem related with JWT based auth. What should I check? -
How to check value getting none in modelserializer
I am having one issue I am having two serializers class PetSerializer(ModelSerializer): pet = AnimalSerilaizer (read_only = True) fields = ('id', 'pet') class Meta: model = Pet class AnimalSerializer(ModelSerializer): name = SerializerMethodField() color = SerializerMethodField() category = SerializerMethodField() photo = SerializerMethodField() class Meta: model = Animal fields = ('id', 'name', 'color', 'category', 'photo') def get_name(self, animal): return '{} {}'.format(animal.first_name, animal.last_name) def get_color(self, animal): return animal.color def get_category(self, animal): return animal.category def get_photo(self, animal): return animal.photo My Issue is When I am calling Pet Serializer if there is any object I am getting values..... If there is no objects I am getting none I need to change the response the "none" in string format . -
How to provide different pages to user accounts after login (Django Project)?
I am currently working on a django web app for an email broadcast service and was wondering how I would provide the different outboxes for the different users, so I can display which messages each user has sent in their outbox.I am working with an html template by Ra-themes. -
How to search for a field in django model which is present in another model
I have a model question , submissions , users submissions has many to many relationship with users and questions So basically submissions has the following fields: questions users time score is_solved When displaying questions to the user I am also displaying whether that particular question has been solved by the user or not. So, if is_solved is true I will display "solved" I am returning all questions to my html page as well as all the submissions user has made and I'm using a loop for question in questions // check if solved // display solved // else do nothing end for My question is how do I check for submissions.solved for each question in the loop -
How to aggreagte Django data model and render them in a table
My model contains a daily campaigns data. A campaign equal to an insertion_order(variable in the models) I would like to aggregate data from my mdel (like summing columns by insertion_order. from django.db import models class TabSource(models.Model): date=models.DateField() dsp=models.CharField(max_length=30) advertiser=models.CharField(max_length=100) insertion_order=models.CharField(max_length=300) insertion_order_id models.IntegerField() strategy_name=models.CharField(max_length=300) creative_name=models.CharField(max_length=400) spent_budget=models.DecimalField(null=True, max_digits=2) impressions=models.IntegerField() clics=models.IntegerField() conversions=models.IntegerField() post_clics_conversions=models.IntegerField() post_view_conversions=models.IntegerField() def __unicode__(self): return "{} {}".format(self.dsp, self.insertion_order) -
django shell freezes when running client.get(reverse)
So I was trying to learn django and going through the tutorials when something weird happened. On the testing views part of the tutorial, I was asked to run a client in shell and I tried it but at some point my console freezes. Here is the code I've been running on the console: PS D:\Users\rrocha\OneDrive\Documents\Material de Estudo\Django\mysite> python manage.py shell Python 3.7.6 (default, Jan 8 2020, 20:23:39) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from django.test.utils import setup_test_environment >>> setup_test_environment() >>> from django.test import Client >>> client = Client() >>> response = client.get('/') Not Found: / >>> response.status_code 404 >>> from django.urls import reverse >>> response = client.get(reverse('polls:index')) The console stops responding when I run the last line. Does anyone have any idea of what I might be doing wrong? -
Gunicorn service fails to start
Gunicorn not starting Hi, I expect this is not the right subreddit for this unfortunately, but becuse it is a django application I've come here as a starting point. But for some reason, gunicorn service will not start on one of my servers. The gunicorn.service and the gunicorn.socket files are identical and in identical locations (I am building a staging server so it must be as close to the other one as possible, the other one is running fine). Can anyone see what might be the issue gunicorn.service: #!/bin/sh [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=pcc Group=nginx WorkingDirectory=/home/rob/myproject ExecStart=/home/rob/anaconda3/envs/django_env/bin/gunicorn --workers 3 --bind unix:/run/gunicorn.sock myproject.wsgi:application [Install] WantedBy=multi-user.target gunicorn status: (django_env) [rob@pcc-home-page run]$ sudo systemctl status gunicorn ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: disabled) Active: failed (Result: exit-code) since Wed 2020-03-11 12:45:25 UTC; 13s ago Process: 1466 ExecStart=/home/rob/anaconda3/envs/django_env/bin/gunicorn --workers 3 --bind unix:/run/gunicorn.sock myproject.wsgi:application (code=exited, status=203/EXEC) Main PID: 1466 (code=exited, status=203/EXEC) Mar 11 12:45:25 pcc-home-page.novalocal systemd[1]: Started gunicorn daemon. Mar 11 12:45:25 pcc-home-page.novalocal systemd[1]: gunicorn.service: main process exited, code=exited, status=203/EXEC Mar 11 12:45:25 pcc-home-page.novalocal systemd[1]: Unit gunicorn.service entered failed state. Mar 11 12:45:25 pcc-home-page.novalocal systemd[1]: gunicorn.service failed. Some extra info: Server is running CentOS, Django is purely running … -
Django - check if two password hashes are of same raw password
I want to keep track of user password change history, and display a warning if their current password is used by them before. To note, I don't want to prevent a user from setting a password if it is used before, I want to let them set the password, but just display a warning afterwards. So what I'm looking for is NOT a password validator. I know that while Django saves user passwords in the db, it creates a hash of the password, using a random salt. So 2 hashes of the same password will not be the same. Still, is it possible to tell if 2 different password hashes are created with the same raw password as the input? -
Django template - iterate a list of tuples, each tuple is a string, dictionary
I have a dictionary that has been turned into a sorted list, which creates the below: monthly_spend_provider = sorted(monthly_spend_provider.items(), key=lambda item: item[1]['cost'], reverse=True) monthly_spend_provider [ ('PROVIDER A', {'cost': Decimal('10000'), 'symbol': '£'}), ('PROVIDER B', {'cost': Decimal('9000'), 'symbol': '$'}), ('PROVIDER C', {'cost': Decimal('8000'), 'symbol': '$'}), ('PROVIDER D', {'cost': Decimal('7000'), 'symbol': '£'}), ] now im trying to access the data in the tuples in a Django template thus far unsucessfully. I thought the below would of worked but it hasn't {% for provider in monthly_provider_country %} {% for data in provider %} <h3>{{ provider }} {{ data.symbol }} {{ data.cost|currency }}</h3> {% endfor %} {% endfor %} can I do this in a template or is there a way to turn the sorted list back into an easier format to output into a template? Thanks -
How to add model form field in the constructor?
I am trying to add a field in a ModelForm but only if a certain condition is met, which is passed through the constructor, so I can't just do: class MyForm(models.ModelForm): class Meta: model = MyModel fields = ['myfield'] I know I can manually add it like this: class MyForm(models.ModelForm): def __init__(self, condition, *args, **kwargs): if condition: self.fields['myfield'] = forms.CharField() But that would be missing attributes from the model definition (max_length, help_text, validators...), not to mention the actual initial and data values if the instance exists. PS: yes I'm on Django 1.8, don't ask why. -
Django Model validation based on a field value of another Model
I have this Django model: from accounts.models import Account class BankOperation(models.Model): created_at = models.DateTimeField(auto_now_add=True) account = models.ForeignKey(Account, on_delete=models.CASCADE) operation_import = models.FloatField(default=0.0) I want to make sure that the operation_import is not higher than account.balance what is the official way to this? I have seen some answers talking about overriding the save() method but others advise against it. should i add a pre-save signal and throw some kind of exception? Is there a way to create a field validator that accepts parameters? so maybe something like: def validate_bank_operation_import(value, account_balance): if value > account_balance: raise ValidationError("Bank operation import is higher than account balance!") and inside my model i change the field to: operation_import = models.FloatField(default=0.0, validators=[validate_bank_operation_import]) But can i pass parameters to a validator? if yes, how do I do it? perhaps there is another to do this validation! -
Setting the field value of a form in view.py
My django website would like to allow logged in users to post a recipe. The recipe model is linked to the user model and as such requires a valid user instance. I would like the Recipe form to automatically assign the postedby field to the instance of the logged in user. So far I have attempted to pass in a dictionary, storing the user's name, to the form instance. as shown in the view However, the constructor method is not receiving the data and is rendering the form but with a failed attempt to submit. I cannot store the data without postedby field having a valid instance as the model throws the following error: Exception Value:UserProfile matching query does not exist. I have also tried to do the following in views.py; @login_required def add_recipe(request): form = RecipeForm() form.fields['postedby'] = UserProfile.objects.get(user=User.objects.get(username=request.user.__str__())) context_dict = {'form':form} if request.method == 'POST': ... However this overwrites the postedby form view to be rendered and raises and error. views.py @login_required def add_recipe(request): form = RecipeForm({'user':request.user}) context_dict = {} #print(form.fields['postedby'].queryset) if request.method == 'POST': form = RecipeForm(request.POST) if form.is_valid(): form.save(commit=True) return redirect(reverse('spatula:index')) else: print(form.errors) context_dict['form'] = form return render(request, 'spatula/add_recipe.html', context=context_dict) The RecipeForm is as follows: class … -
ModelChoiceField always raises : “Select a valid choice. That choice is not one of the available choices”
In forms I have multiple dependent choice fields. but I am getting same error for all the dependent choice fields i tried but it wont come please help me.I am fresher. forms.py class IssuecreateForm(forms.ModelForm): def __init__(self,*args, **kwargs,): self.projects = kwargs.pop("projects",None) # self.issues = kwargs.pop("issues",None) # self.rootcause = kwargs.pop("rootcause",None) super(IssuecreateForm, self).__init__(*args, **kwargs) self.fields['SUMMARY'].widget.attrs.update({'class' : 'form-control','placeholder': 'Enter Summary'}) self.fields['SUMMARY'].label='Summary' self.fields['DESCRIPTION'].widget.attrs.update({'class' : 'form-control mb-4','placeholder': 'Enter Description'},required=False) self.fields['DESCRIPTION'].label='Description' self.fields['ENVIRONMENT'].widget.attrs.update({'class' : 'form-control mb-4','placeholder': 'Enter Description'},required=False) self.fields['ENVIRONMENT'].label='Environment' self.fields['PROJECT'].queryset = self.projects self.fields['LINKED_ISSUES'].choices = [(x.ID, x.SUMMARY) for x in Issues.objects.all()] LABELS =forms.MultipleChoiceField(widget=forms.Select({'class': 'lable-select', 'name':"lable-select", "multiple":"multiple"}), choices=OPTIONS,required=False) CREATED_DATE_TIME=forms.DateTimeField(initial=datetime.datetime.today(),required=False) PROJECT = MyModelChoiceField(queryset=Project.objects.all(),widget=CustomSelectOption(attrs={'class':'mt-2'})) PRIORITY = MyModelChoiceField(queryset=Priority.objects.none(),widget=CustomSelectOption(attrs={'class':'mt-2','name':'issue-types'})) TYPE = MyModelChoiceField(queryset=IssueType.objects.none(),widget=CustomSelectOption(attrs={'class':'mt-2'})) LINKED_ISSUE_TYPES = ModelChoiceField(queryset=LinkedIssueType.objects.none(), empty_label='----------Select Linked Issue Type---------') # STATUS = ModelChoiceField(queryset=IssueStatus.objects.none(), empty_label='----------Select Status---------') RESOLUTIONS = ModelChoiceField(queryset=Resolution.objects.none(),required=False, empty_label='----------Select Resolution---------') ROOT_CAUSES = ModelChoiceField(queryset=RootCause.objects.none(),required=False, empty_label='----------Select Rootcause---------') PROCESS_AREAS = ModelChoiceField(queryset=ProcessArea.objects.none(),required=False, empty_label='----------Select Process Area---------') FUNCTIONAL_AREAS = ModelChoiceField(queryset=FunctionalArea.objects.none(),required=False, empty_label='----------Select Functional Area---------') # DEFECT_TYPE = ModelChoiceField(queryset=DefectType.objects.none(), empty_label='----------Select Defect Type---------') ASSIGNEE = MyModelChoiceField(queryset= PmUser.objects.none(),widget=CustomSelectOption(attrs={'class':'mt-2'}),required=False) REPORTER = MyModelChoiceField(queryset= PmUser.objects.none(),widget=CustomSelectOption(attrs={'class':'mt-2'}),required=False) SPRINTS = ModelChoiceField(queryset=Sprint.objects.none(),required=False, empty_label='----------Select Sprint---------') LINKED_ISSUES = forms.MultipleChoiceField(widget=forms.Select({"class":"issue-list", "name":"issue-list", "multiple":"multiple"}),choices = [],required=False) # EPIC_LINK = forms.MultipleChoiceField(widget=forms.Select({"class":"issue-list", "name":"issue-list"}),choices = []) DURATION_CHOICES=forms.ChoiceField(widget=forms.RadioSelect(attrs={'placeholder': 'METHOD_TYPE','class':'myclass'}),required=False,choices=DURATION_CHOICES) class Meta: model = Issues fields ='__all__' exclude=['CREATOR','UPDATOR','CREATED_DATE_TIME','UPDATED_DATE_TIME','EPIC_LINK','WATCHER','PARENT','LINKED_ISSUES','ORDER','SERIAL_NUMBER','COLOR','DEFECT_TYPE','STATUS','EPIC_NAME'] widgets = { 'START_DATE': DateInput(), 'DUE_DATE': DateInput(), 'ESTIMATION_TIME': DurationInput(), } -
Django models foreignkey default value
There was no manager in the posts I created before. When I add the manager, I want the default value or I am asked to enter it manually. When I enter 'None' I get an error like this; django.db.utils.IntegrityError: NOT NULL constraint failed: new__Core_post.manager_id I cannot export PostManager as the default value. Is there another way or another solution to give? class User(models.Model): #... posts = models.ManyToManyField('Post', blank=True) class Post(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) #... manager = models.ForeignKey('PostManager', on_delete=models.CASCADE) class PostManager(models.Model): #... Sorry for my bad english. -
Obtain all the columns from my model in django
I want to obtain all the info from one table of my database in django, I'm doing this, from django.shortcuts import render # Create your views here. from Platform_App.models import fleets def list_fleets(request): fleet = fleets.objects.all() return render(request, template_name='fleets.html', context={'Fleet':fleet}) But it shows an error in the line below, concretely in fleets. fleet = fleets.objects.all() It says, class fleets has no objects member My model is the following: class fleets(models.Model): fleet_id = models.IntegerField(primary_key=True) fleet_name = models.CharField(max_length=20) description = models.CharField(max_length=40, blank=True, null=True) If fleet = fleets.objects.all() is not correct, how I have to do it to take all the columns of my table?? Probably a easy question, but I'm newbie. Thank you very much!!!! -
Can't connect to website with LetsEncrypt certificate - nginx
I'd like to add ssl certificate to my django app. I've followed tutorial so the nginx config for domain was changed but now it looks like generated certificate is incorrect. nginx conf before certbot modifications server { listen 80; listen [::]:80; server_name doamin.com www.domain.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/poul3r/doamin.com; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } and after certbot action server { server_name doamin.com www.doamin.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/poul3r/doamin.com; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } listen [::]:443 ssl ipv6only=on; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/doamin.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/doamin.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = doamin.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; listen [::]:80; server_name doamin.com www.doamin.com; return 404; # managed by Certbot } What I'm doing wrong or what could went wrong during letsencypt implementation ? -
Importing a JS file on Django
I created a simple file called main.js. In this file, i defined a function: function hello(){ console.log('hello') } Now i'm trying to import the file on a template and call the function from there. Here is what i tried: <script type="text/javascript" charset="{% static 'main.js' %}"> hello() </script> But this is giving me the following error: Uncaught ReferenceError: hello is not defined Why is this happening? Am i not importing the file? This is where main.js is located: static -> main.js And here is how my static directory is defined on Django: STATIC_URL = '/static/' My static directory contains a lot of other files and i'm not having problems with those; can someone help me find what i'm doing wrong with this one? Every advice is appreciated -
How to get only one object from ManyToOne table, instead of queryset?
Table Images: id| image | item_id 15|some/path| 45 16|some/path| 45 17|some/path| 45 First try: recommended_items = Item.objects.all().filter(rating__gte=9) // All my items (`item_id` column) for item in recommended_items : image = Images.objects.get(item=item.id)[:1] It works for first item with id=45 but for the rest it returns error: Images matching query does not exist. Second try: for item in recommended_items : image = Images.objects.filter(item=item)[:1] Now it works for all items, existing or not, but it returns iterate object and I should add for loop for just one object, like this: for i in image: print(i.image) What is the right way to handle this ? I want just one record (the last one if it is possible) -
Why am I getting this error while typing the command- makemigrations
from django.db import models # Create your models here. class Products(models.Model): title = models.TextField() description = models.TextField() price = models.TextField() I don't know why I get this error: Traceback (most recent call last): File "Blank/manage.py", line 21, in main() File "Blank/manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\lenovo\PycharmProjects\Django\venv\lib\site-packages\django\core\management__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\lenovo\PycharmProjects\Django\venv\lib\site-packages\django\core\management__init__.py", line 377, in execute django.setup() File "C:\Users\lenovo\PycharmProjects\Django\venv\lib\site-packages\django__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\lenovo\PycharmProjects\Django\venv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\lenovo\PycharmProjects\Django\venv\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\lenovo\AppData\Local\Programs\Python\Python37-32\lib\importlib__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1006, in _gcd_import File "", line 983, in _find_and_load File "", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'products' -
DRF: how to change the value of the model fields before saving to the database
If I need to change some fields values before saving to database as I think models method clear() is suitable. But I can't call him despite all my efforts. For example fields email I need set to lowercase and fields nda I need set as null models.py class Vendors(models.Model): nda = models.DateField(blank=True, null=True) parent = models.OneToOneField('Vendors', models.DO_NOTHING, blank=True, null=True) def clean(self): if self.nda == "": self.nda = None class VendorContacts(models.Model): .... vendor = models.ForeignKey('Vendors', related_name='contacts', on_delete=models.CASCADE) email = models.CharField(max_length=80, blank=True, null=True, unique=True) def clean(self): if self.email: self.email = self.email.lower() serializer.py class VendorContactSerializer(serializers.ModelSerializer): class Meta: model = VendorContacts fields = ( ... 'email',) class VendorsSerializer(serializers.ModelSerializer): contacts = VendorContactSerializer(many=True) class Meta: model = Vendors fields = (... 'nda', 'contacts', ) def create(self, validated_data): contact_data = validated_data.pop('contacts') vendor = Vendors.objects.create(**validated_data) for data in contact_data: VendorContacts.objects.create(vendor=vendor, **data) return vendor views.py class VendorsCreateView(APIView): """Create new vendor instances from form""" permission_classes = (permissions.AllowAny,) serializer_class = VendorsSerializer def post(self, request, *args, **kwargs): serializer = VendorsSerializer(data=request.data) try: serializer.is_valid(raise_exception=True) serializer.save() except ValidationError: return Response({"errors": (serializer.errors,)}, status=status.HTTP_400_BAD_REQUEST) else: return Response(request.data, status=status.HTTP_200_OK) As I learned from the documentation Django Rest Framework serializers do not call the Model.clean when validating model serializers In dealing with this problem, I found two ways to … -
Django increasing value in database on update
i have table for inventory where is Qty column, i will like to add Qty using form to sum new value with already existed in database my class based view in views.py looks like : class ItemUpdateView(LoginRequiredMixin, UpdateView): model = Stock template_name = 'users/item_update_form.html' fields = ['qty'] right now im getting this output : screenshot from page view i will like to have empty Qty Field to type new value and after pressing Add increase value already existing in database with this new value -
Django Choice Field similar as in Admin (Permissions)
Unfortunately we have some really long drop down lists for our users to choose from and the way the django admin implemented their permissions ui really looks like a good solution for this, but for the life of me I can't find any examples how to implement something similar? Does anyone has any tipps? (I currently use "Select2MultipleWidget" to at least make it somewhat manageable) -
NOT NULL constraint failed: complaint_complaint.resident_id
I am writing an app in which people can submit their complaints related to some issues. After the form is submitted, it is supposed to redirect to the page where the details of the complaint are mentioned like area of the complaint, title, description etc. But after the form is submitted, it throws IntegrityError. I read about it and went through some of the solutions: Someone suggested that I delete some past migrations and run them again. I cleared the migrations, ran them again and made some posts through the admin but it is throwing the same error. Some posts suggest that null=True, blank=True should be added but I do not understand where they should be added in my case. I also don't want to add null=True, blank=True because I don't want any field to be left blank. Below is my models.py: from django.db import models from django.urls import reverse # Create your models here. class Complaint(models.Model): """ Details of the complaint """ resident = models.ForeignKey('auth.User', on_delete=models.CASCADE) AREA = [('PL', 'Plumbing'), ('EL', 'Electricity'), ('CP', 'Carpenter'), ('CO', 'Construction'), ('DS', 'Disputes'), ('OT', 'Other'),] matter = models.CharField(max_length=2, choices=AREA) title = models.CharField(max_length=200) text = models.TextField() date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title def get_absolute_url(self): …