Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django test resolves by for loop
I am doing some test in Django. I use fixtures to pre load some data and test API POST. In my POST, I want to link some data by foreign key. The test behavior is odd. I need to place a for loop in order for it to succeed. Here's my example for my fixtures: [ { "model": "apps.track", "pk": 1, "fields": { "name": "Love Song # 1", "album": null } }, { "model": "apps.track", "pk": 2, "fields": { "name": "Love Song # 2", "album": null } } ] Here's my test: class TestPost(TestCase): fixtures = ['fixtures/sample'] def setUp(self): self.album = { 'name': 'Love Songs Album', 'tracks': [ {'id': 1}, {'id': 2} ] } def test_post(self): c = Client() response = c.post( '/admin/login/', {'username': 'admin', 'password': 'passwordpassword'}) response = c.post('/apps/albums/', data=json.dumps(self.album), content_type='application/json') album = Album.objects.latest('id') tracks = Track.objects.filter(album=album).all() self.assertEqual(tracks[0].id, 1) self.assertEqual(tracks[1].id, 2) The test fails and only finds tracks id=2 but not tracks id=1. However when I add a for loop before the test assertions, the test succeeds. Here's the magic for loop: for track in tracks: print("TRACK", track.id) I want to know if there is any reason behind this. -
How can I make this query in Django?
I have theese fields(test_type, status, begin_time, and_time).The 'status' field has three state(0, 1,or 2). I want to make a queryset where: test_type = 'difficult') and (if status==1 and begin_time + 2x(end_time - begin_time) < timezone.now()) and (if status==2 and end_time < timezone.now()) then select theese fields. If the status state=0 I dont want to select that field. How can i make this queryset with Django ORM? -
best way to optimize django critical render path
I have a view which for every request will do some calculations about 1 second and then send result to render template function (return an html response). As noted here the html header section should be sent as early as possible to let browser start downloading other blocking assets (CSS) while downloading rest of html. It also minimizes time of showing First Paint, FCP which will improve user experience. In django by using render function we will send entire result after all calculation is done: from django.shortcuts import render def view(request): # calculate context (it may take about 1 seconds) return render(request, 'result.html', context) What is the best way to send html header response as early as possible? I know about StreamingHttpResponse but I'm not sure if it's a good fit for this problem (django docs: You might want to do this if generating the response takes too long or uses too much memory. For instance, it’s useful for generating large CSV files.) -
Initial data creation fails with data migration
It's my intent to create some initial model instances through a data migration with some JSON data. Upon calling json.load() on the JSON file, I'm iterating over each dictionary and its keys. Any key with white space is supposed to be replaced with a new string containing underscores. This is being done to unpack the dictionary when creating an model instance with Model.create(). What should be refactored to get the expected result? Actual outcome: Not all keys that have white space get replaced with new strings that contain underscores. Expected outcome: All keys that have white space get replaced with new strings that contain underscores. #models.py from django.db import models # Create your models here. class Item(models.Model): name = models.CharField(unique=True, max_length=255) image_filename = models.ImageField() category_type= models.CharField(max_length=255, blank=True) color = models.CharField(max_length=255, blank=True) current_condition = models.CharField(max_length=255, blank=True) def __str__(self): return self.name #data migration # Generated by Django 2.2.7 on 2019-11-30 23:21 import json from django.db import migrations def create_minerals(apps, schema_editor): Mineral = apps.get_model('minerals', 'Mineral') with open('my_file', 'r', encoding='utf-8') as data_file: uploaded_minerals_data = json.load(data_file) for mineral_dict in uploaded_minerals_data: mineral_name_data = mineral_dict.keys() for name in mineral_name_data: if " " in name: value = mineral_dict.pop(name) new_name = name.replace(" ", "_") mineral_dict[new_name] = value else: continue … -
Django: html not displaying form using block content
enter image description here //form.html {% load crispy_forms_tags %} {% block content %} <form {% if form_id %} id='{{ form_id }}' {% endif %} class='form' method='POST' action="{% if action_url %}{{ action_url }}{% endif %}"> {% csrf_token %} {{ form|crispy }} <input class="btn btn-primary" type="submit" value="{{ btn_title }}" /> </form> {% endblock %} //list_view.html {% extends "base.html" %} {% block content %} <div class="row"> <div class='col-sm-3 col-xs-12' style='background-color:red;'> <h1>{{ request.user }}</h1> </div> <div class='col-sm-9 '> {% if not request.GET.q %} <div class=""> {% include "tweets/form.html" with form=create_form action_url=create_url btn_title='Tweet' form_id='tweet-form' %} </div> <hr> {% endif %} <div id="tweet-container"> </div> </div> </div> {% endblock content %} For some reason when I try to use the form.html within the block content of list_view.html it only returns {% include "tweets/form.html" with form=create_form action_url=create_url btn_title='Tweet' form_id='tweet-form' %} as you can see in the photo I posted. im trying to make it a text area with a submit button. Does anyone have any suggestions -
How to upload multiple files (images) using django-rest-framework?
I'm writing a REST API, I haven't tried and have no clue how to upload multiple photos using django. Is there a separate serializer that I have to use or can I just use the serializer with the param 'many=True' similar to bulk data insertion? A python snippet would really be useful. Thanks in advance! -
Reverse access to OneToOne field in an abstract model
Suppose I have the following database structure: class Building(models.Model): # ... class AbstractBuilding(models.Model): building = models.OneToOneField(Building, on_delete=models.CASCADE, primary_key=True) # ... class Meta: abstract = True class Office(AbstractBuilding): # ... class Lab(AbstractBuilding): # ... class PowerPlant(AbstractBuilding): # ... If I have an Office object, it's easy to get the corresponding Building through the one-to-one field (e.g. office_object.building returns a Building). However, suppose I have a Building instead. How can I get the corresponding Office (or Lab or PowerPlant) from the Building object? -
No module named 'django.contrib.staticfiles.templatetags'
I have been breaking my head over this for a full day but can't figure out the problem. It happened after I copied my Django project from one PC to another. Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/username/opt/anaconda3/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/Users/username/opt/anaconda3/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/username/opt/anaconda3/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/username/opt/anaconda3/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Users/username/opt/anaconda3/lib/python3.7/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/Users/username/opt/anaconda3/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/Users/username/opt/anaconda3/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/username/opt/anaconda3/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/username/opt/anaconda3/lib/python3.7/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/Users/username/opt/anaconda3/lib/python3.7/site-packages/django/contrib/admin/apps.py", line 24, in ready self.module.autodiscover() File "/Users/username/opt/anaconda3/lib/python3.7/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "/Users/username/opt/anaconda3/lib/python3.7/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/Users/username/opt/anaconda3/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/saitohiromasa/opt/anaconda3/lib/python3.7/site-packages/django_summernote/admin.py", line 5, in <module> from django_summernote.widgets import SummernoteWidget, … -
How can i reduce my coding length in my below code?
Because i am a newbie so its really hard to understand code having much length..If i can reduce the length of code then how can i reduce it please explain someone in the below code. class Attachments(models.Model): created_by = models.ForeignKey( User, related_name='attachment_created_by', on_delete=models.SET_NULL, null=True) file_name = models.CharField(max_length=60) created_on = models.DateTimeField(_("Created on"), auto_now_add=True) attachment = models.FileField( max_length=1001, upload_to='attachments/%Y/%m/') lead = models.ForeignKey( 'leads.Lead', null=True, blank=True, related_name='lead_attachment', on_delete=models.CASCADE) account = models.ForeignKey( 'accounts.Account', null=True, blank=True, related_name='account_attachment', on_delete=models.CASCADE) contact = models.ForeignKey( 'contacts.Contact', on_delete=models.CASCADE, related_name='contact_attachment', blank=True, null=True) opportunity = models.ForeignKey( 'opportunity.Opportunity', blank=True, null=True, on_delete=models.CASCADE, related_name='opportunity_attachment') case = models.ForeignKey( 'cases.Case', blank=True, null=True, on_delete=models.CASCADE, related_name='case_attachment') task = models.ForeignKey('tasks.Task', blank=True, null=True, related_name='tasks_attachment', on_delete=models.CASCADE) invoice = models.ForeignKey('invoices.Invoice', blank=True, null=True, related_name='invoice_attachment', on_delete=models.CASCADE) event = models.ForeignKey('events.Event', blank=True, null=True, related_name='events_attachment', on_delete=models.CASCADE) def file_type(self): name_ext_list = self.attachment.url.split(".") if (len(name_ext_list) > 1): ext = name_ext_list[int(len(name_ext_list) - 1)] if is_document_file_audio(ext): return ("audio", "fa fa-file-audio") if is_document_file_video(ext): return ("video", "fa fa-file-video") if is_document_file_image(ext): return ("image", "fa fa-file-image") if is_document_file_pdf(ext): return ("pdf", "fa fa-file-pdf") if is_document_file_code(ext): return ("code", "fa fa-file-code") if is_document_file_text(ext): return ("text", "fa fa-file-alt") if is_document_file_sheet(ext): return ("sheet", "fa fa-file-excel") if is_document_file_zip(ext): return ("zip", "fa fa-file-archive") return ("file", "fa fa-file") return ("file", "fa fa-file") def get_file_type_display(self): if self.attachment: return self.file_type()[1] return None @property def created_on_arrow(self): return … -
Migrating to Django 2.2 from 1.11 -- old migrations without on_delete in ForeignKey break everything
I'm working on upgrading my legacy application from Django 1.11.13 to 2.2.8. I've dutifully addressed every compatibility issue, but I've hit one I can't figure out how to resolve. When I try to start the webserver in my local environment, I get this error (only showing the end of the full error trace that appears): File "/Users/me/my_app/my_model/migrations/0001_initial.py", line 37, in Migration ('entry', models.ForeignKey(to='my_model.Entry')), TypeError: __init__() missing 1 required positional argument: 'on_delete' I understand why on_delete is now required -- I just spent a while updating my models everywhere to accommodate this change -- but I have no idea how to fix this particular issue without going through dozens of old migrations files to make them conform?! I tried squashmigrations to at least collapse the number of places I have to clean up, but I got the same exact TypeError. I tried to use the old version of Django for squashmigrations. I was successful in avoiding the TypeError, but ended up with a huge mess of circular import errors. Since I don't actually need the migration history to roll back, I tried to follow these instructions (scenario 2) to clear the migration history while keeping the existing database, but I couldn't … -
Can I post the javascript array to the database in django framework?
I am new to django, I am having an users table and designs table as given below class designs(models.Model): id=models.IntegerField(primary_key=True) image = models.ImageField(upload_to='images') content = models.CharField(max_length=50,default='0000000') > class users(models.Model): email = models.CharField(max_length=50,default='0000000') password = models.CharField(max_length=50,default='0000000') design = models.ManyToManyField(designs) The user will click the designs he want it is a multi select and after clicking every the every design i wrote a javascript array to store the details of every design clicked by the user like this styles=[2, "../static/images/2.jpg", "Rustic & Warm", 3, "../static/images/3.jpg",…] So,in the form I took hidden input of design_id like this <form action="{% url 'car:user_register' %}" method="POST"> > {% csrf_token %} > <div class="form-group"> > <label for="design_id"></label> > <input type="hidden" name="design_id" class="form-control" value="styles"required> > </div> > > And my views.py def user_register(request): if request.method == 'POST': design_id=request.POST.GET('styles[]') email = request.POST['email'] password = request.POST['password'] user = users(password=password,email=email,design_id=design_id) user.save() return render(request,'home.html') Is that a correct way of getting and posting that javascript array in the database -
How to populate initial values of form from queryset
I have a FormView with a get_initial method which I am trying to use to populate the form. I am trying to get the EmployeeTypes of the receiver of the memo as values in the form. def get_initial(self): initial = super(NotificationView, self).get_initial() users = Memo.objects.filter(id=self.kwargs['pk']).values('receiver__employee_type') initial['receiving_groups'] = users return initial There are 2 issues here.. This returns a Queryset which looks like: <QuerySet [{'receiver__employee_type': 'Bartender'}, {'receiver__employee_type': 'Supervisor'}]> when I really need the fields in the form to be the EmployeeType itself. Most importantly - the form isn't even rendering these fields. Here is the form just in case: class MemoNotificationForm(forms.Form): class Meta: fields = [ 'receiving_groups' ] receiving_groups = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple) How do I populate the fields of the form? -
Error while updating mongodatabase collections from django app using djongo
I am facing an error. I am trying out the polls tutorial as provided in the django documentation. The problem is with the django 'F' function. I am trying to update the number of votes for a choice. If I load the choice object into python memory and do the normal numeric addition it is working. But if I use choice.update(votes=F('votes')+1) then it is giving me the following error. djongo.sql2mongo.SQLDecodeError: FAILED SQL: UPDATE "poll_choice" SET "question_id" = %(0)s, "choice_text" = %(1)s, "votes" = ("poll_choice"."votes" + %(2)s) WHERE "poll_choice"."id" = %(3)s Params: (1, 'huntress', 1, 3) If we observe %(2)s is supposed to be a number and not a string. But it is going as a string. Please help how I can resolve this . I am using djongo 1.2.38 with sqlparse version 0.2.4. -
Django Model seeking alternative to many to many fields
I am writing an exam system, below is my model: class Exam(models.Model): name = models.CharField( max_length=100 ) class Topic(models.Model): name = models.CharField( max_length=50 ) class Question(models.Model): title = models.CharField( max_length=100 ) topic = models.ForeignKey( Topic ) class Choice(models.Model): question = models.ForeignKey( Question, on_delete=models.CASCADE ) choice_text = models.CharField( max_length=200 ) is_right_answer = models.BooleanField( default=False ) I want when I create an exam, i can give multiple topics like math, physics, business etc and then i can query all the questions related that topics and show in the frontend. My problem only in exam creation, i am not getting should I use ManyToManyField or there is any alternative solution I just want to select multiple topic during i create an exam. Can anyone help me in this case? -
Why is my Django form is not displaying anything?
I am following a tutorial in which we will create a form to hold simple object parameters. Here's the code: forms.py from django.forms import ModelForm from .models import Item class ItemForm(ModelForm): class Meta: model = Item fields = ['item_name', 'item_desc', 'item_price', 'item_image'] models.py from django.db import models class Item(models.Model): def __str__(self): return self.item_name item_name = models.CharField(max_length = 200) item_desc = models.CharField(max_length= 200) item_price = models.IntegerField() item_image = models.CharField(max_length=500, default ="https://i.jamesvillas.co.uk/images/jvh/holiday-destinations/resort/food-placeholder.jpg" ) urls.py from . import views from django.urls import path urlpatterns = [ path('', views.index, name = 'index'), path('item/', views.item, name = 'item'), path('info/', views.info, name = "info"), path('<int:item_id>/', views.detail, name = "detail" ), #add form path('add', views.create_item, name = "create"), ] views.py from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Item from django.template import loader from .forms import ItemForm #Some code here def create_item(request): form = ItemForm(request.POST or None) if (form.is_valid()): form.save() return redirect('food/index') return render(request, 'food/item-form.html', {'form': form}) food/item-form.html <form method = "POST"> {% csrf_token %} {{ form }} <button type= "Submit" >Save</button> </form> Now when I go to http://localhost:8000/food/add, it displays an empty page! I have followed the tutorial the exact same way then why is My project not working? -
Join and format array of objects in Python
I want to join and format values and array of objects to a string in python. Is there any way for me to do that? url = "https://google.com", search = "thai food", search_res = [ { "restaurant": "Siam Palace", "rating": "4.5" }, { "restaurant": "Bangkok Palace", "rating": "3.5" } ] url = "https://google.com", search = "indian food", search_res = [ { "restaurant": "Taj Palace", "rating": "2.5" }, { "restaurant": "Chennai Express", "rating": "5.0" } ] url = "https://bing.com", search = "thai food", search_res = [ { "restaurant": "Siam Palace", "rating": "1.5" }, { "restaurant": "Bangkok Palace", "rating": "4.5" } ] url = "https://bing.com", search = "indian food", search_res = [ { "restaurant": "Taj Palace", "rating": "4.5" }, { "restaurant": "Chennai Express", "rating": "3.0" } ] I want to be able to format the values as such: If I could make it look like: all_data = [{ url = "https://google.com", results = [{ search = "thai food", search_res = [{ "restaurant": "Siam Palace", "rating": "4.5" }, { "restaurant": "Bangkok Palace", "rating": "3.5" }] }, { search = "Indian food", search_res = [{ "restaurant": "Taj Palace", "rating": "2.5" }, { "restaurant": "CHennai Express", "rating": "5.0" }] }] }, { url = "https://bing.com", … -
Webhost Platform for PostGIS, Django and Celery
I'm currently developing a django web app. I'm trying to decide which platform is best suited to host it. I was considering PythonAnywhere but it seems like they don't support celery or other long running processes. Any suggestions? -
How to initialize form with some parameters of model instance
I would like be able to send SMS/Email notifications manually using the groups/users of a model instance. Let's say the model looks like this: class Memo(models.Model): title = models.CharField(max_length=100) receiver = models.ManyToManyField(EmployeeType, related_name='memos_receiver') I pass the object instance to the view: path('<int:pk>/notify', NotificationView.as_view(), name='memos-notify'), The form and the view are where I am having trouble. I figure I should be able to just pass the forms initial fields right there in the view: class NotificationView(FormView): template_name = 'memos/notification_form.html' form_class = MemoNotificationForm success_url = reverse_lazy('overview') def get_initial(self): initial = super(NotificationView, self).get_initial() memo = Memo.objects.filter(id=id) initial['receiving_groups'] = memo.receiver return initial And the form looks like this: class MemoNotificationForm(forms.Form): class Meta: fields = [ 'receiving_groups' ] receiving_groups = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple) TypeError: int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method' Do I need to initialize the queryset in the form? Would appreciate it if someone could paint me a clear picture of the why and how here. Thank you! -
Crispy Django Form With RadioBox - Using InlineRadios
I want to style in Radio button in Django using Crispy Form. However, I have successful making use of CSS which is applied to the form but I need to display the form n inline format. After rendering the form in my html, I got a put which is not in inline format. I will be very happy if I can more detail about crispy form using radio button or selected button class ViewForm(forms.Form): #django gives a number of predefined fields #CharField and EmailField are only two of them #go through the official docs for more field details VIEWS = ( ('1', 'Likes & Comments'), ('2', 'Subscribers'), ('2', 'App Installs'), ) GENDER = ( ('1', 'Female'), ('2', 'Male') ) AGE = ( ('All', 'All'), ('13 - 24', '13 - 24'), ('25 - 34', '25 - 34'), ('35 - 44', '35 - 44'), ('45 - 54', '45 - 54'), ('55 - 64', '55 - 64'), ) CATEGORY = ( ('Auto', 'Auto'), ('Beauty', 'Beauty'), ('Sport', 'Sport'), ) CHOICES=[('select1','select 1'), ('select2','select 2')] view= forms.ChoiceField(label='BESIDE VIEWS, I ALSO WANT:', widget=forms.RadioSelect, choices=VIEWS) age= forms.ChoiceField(label='AGE?', widget=forms.RadioSelect, choices=AGE) gender = forms.ChoiceField(label='AGE?', widget=forms.RadioSelect, choices=GENDER) location = forms.CharField(max_length=25, required=False) category= forms.CharField(label='CATEGORY', widget=forms.Select(choices=CATEGORY)) keyword = forms.CharField(max_length=50, required=False) my css input[type=radio], … -
Django TestCase object has no attribute 'login'
I have used selenium to test my login method and it works fine. Then, I tried to test other parts of the website. So, I needed to create a user in my test. To do that, I've used client instead of request factory (since there are middleware classes). However, I am getting the error: AttributeError: 'ProjectListTestCase' object has no attribute 'login' I do have a custom authentication backend to allow for email address to be used instead of username: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'phonenumber_field', 'rest_framework', # 3rd party apps 'crispy_forms', # Local apps 'accounts', ... I tried the code in the console: >>> the_client = Client() >>> the_client.login(email='test@testing.com', password='testingPassword') True Here is the code in my test_views.py: from django.core.urlresolvers import reverse from django.core.exceptions import ObjectDoesNotExist, ValidationError from django.test import TestCase from django.test import RequestFactory from model_mommy import mommy from selenium import webdriver from project_profile.models import Project from user_profile.models import UserProfile class ProjectListTestCase(TestCase): def setUp(self): # login the user login = self.client.login(email='test@testing.com', password='testingPassword') print ('Login successful? ', self.login) # Just to see what's going on response = self.client.get(reverse('development:list_view_developmentproject') ) print('response: ', self.response) # Just to see what's going on def test_user_login(self): self.assertEqual(self.response.status_code, 200) Why do I … -
Send mail inside action django-rest-framework
i'm learning django restframework by myself I'm trying to send a mail with sengrid inside an action enter image description here The mail doesn't send Sorry for menglish thank you -
Django background task repeating more than it should
I am trying to run a django background task every 30 seconds, as a test I'm having it print "hello", but instead of printing every 30 seconds it is printing about every second or less very quickly. Here is my code currently: from background_task import background from datetime import timedelta, datetime @background(schedule=datetime.now()) def subscription_job(): print("hello") subscription_job(repeat=30) -
How to make the user visible to al his group activities
I am doing a django-rest-framework project in which one can create groups by adding member’s email id and the logged in user should be able to see all the group activities. I used django-multi-email-field to store the list of emails of respective members Now the user can see his own activities when logged in.How can i make the user visible to all the group activities.Should i create a model inside a model? Please help me. -
Failed lookup for key in templates
I am trying to get Specific List in Dictionary, but first i got the error: "fail to lookup for key", searching on internet I found out a tread with this solution: {% with obj1.page.val2 as val2 %} {{ obj1.val1|default:val2 }} {% endwith %} But It does not work any help here is my code: keyData = '\'' + id + '|' + id2 + '|' + id3 + '\''; console.log(keyData); var val2; try { {% with keyData as val2 %} console.log(val2); datas = {{product_prices_complex_key|get_item:val2|safe}}; {% endwith %} console.log(datas); }catch(err){console.log(err);} KeyData: WA5-8|2|5 And is in the dictionary. Thanks in Advanced -
Django model method error: missing 1 required positional argument: 'self'
I want to do some calculations inside a model and between attributes. I want 3 fields that can be entered by the user to add the model, but those fields get concatenated into a non-editable field that can be used for viewing purposes only. Here is the model I have: class Dossier(models.Model): #Dossiers sinistre numero = models.CharField(max_length=20, default=dossier_number, editable=False) created_by = models.ForeignKey(Prestataire, on_delete=models.SET_NULL, null=True) mat_id = models.CharField(max_length=7, default="123456") mattypes = ( ('A', 'A'), ('B', 'B'), ('C', 'C'), ('D', 'D'), ) mat_symbol = models.CharField(max_length=3, choices=mattypes, default="A") mat_ville = models.CharField(max_length=2, blank = True) def define_matricule(self): if self.mat_symbol == "A" or "B": return str(self.mat_id) + '-' + str(self.mat_symbol) + '-' + str(self.mat_ville) else: return str(self.mat_id) + '-' + str(self.mat_symbol) matricule = models.CharField(max_length=20, default=define_matricule, editable=False) But when I run this, I find this error: Django Version: 2.2.5 Exception Type: TypeError Exception Value: define_matricule() missing 1 required positional argument: 'self' Exception Location: C:\Users\Kaiss Bouali\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\fields\__init__.py in get_default, line 797 Python Executable: C:\Users\Kaiss Bouali\AppData\Local\Programs\Python\Python37\python.exe Here's my traceback: Environment: Request Method: GET Request URL: http://localhost:8000/dossiers/nouveau Django Version: 2.2.5 Python Version: 3.7.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'formtools', 'dashboard.apps.DashboardConfig', 'crispy_forms', 'photologue', 'sortedm2m'] Installed 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'] Traceback: File "C:\Users\Kaiss Bouali\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py" …