Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I redirect to the same page after submitting a form using Django and display the submitted data on that same page?
This is my class based view function Whenever the use finishes to enter the required data and click the submit button. I want the page to reload so user can see the data they have submitted. I don't want to redirect the user to another page. But the app behaves differently. I'm trying to see how I can manage to make this work please Any hint will be helpful. Thank you in advance. class homeView(View): def get(self, request): data = recipemeal.objects.all().order_by("-id") context ={ "recipes":data, "form":RecipeForm() } return render(request, "index.html", context) def post(self, request): form = RecipeForm(request.POST) data = recipemeal.objects.all().order_by("-id") if form.is_valid(): form.save(commit=True) return HttpResponseRedirect(reverse("home")) else: context = { "recipes": data, "form": RecipeForm() } return render(request, "index.html", context) urlpatterns = [ path("", views.homeView.as_view(), name="home"), ] <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h2>Hi there, my name is Wilkenson</h2> <section> <div class="container"> <div> <form method="POST"> {% csrf_token %} {{ form }} <button class="btn" type="submit">Add Data</button> </form> </div> <div> <form action="/" method="POST"> {% csrf_token %} <button class=" button generate-pdf">Generate Plan</button> </form> </div> {% if recipes %} <table> <tr> <th>Recipe No.</th> <th>Day-Time</th> <th>Recipe Name</th> <th>Description</th> <th>Action</th> </tr> {% for item in recipes %} <tr> <td>{{item.id}}</td> <td>{{item.date}}</td> <td>{{item.title}}</td> … -
How to secure a refresh token in a JWT system when it's sent as an httpOnly cookie
In my React + Django project, I’m currently sending the refresh token as an HttpOnly cookie. The problem with HttpOnly cookies is that they are automatically sent by the browser, which makes them vulnerable to CSRF attacks. To address this, I decided to add a CSRF token for the refresh request. However, the issue I’m facing is that I’m unable to read the CSRF token using JavaScript. I think this is because my frontend and backend are on different domains. When I searched online, I found that cross-site cookies can’t be read by JavaScript. If that’s true, what are the possible ways to protect the refresh token request? -
custom filter for filter_horizontal admin in django
I have the following models where a deck have a many to many relationship with problems and problems can have tags from django.utils import timezone from django.db import models from taggit.models import TaggedItemBase from taggit.managers import TaggableManager # Create your models here. class TaggedProblem(TaggedItemBase): content_object = models.ForeignKey('Problem', on_delete=models.CASCADE) class Problem(models.Model): title = models.CharField(max_length=200) body = models.CharField(max_length=10000) pub_date = models.DateTimeField("date published", default=timezone.now()) tags = TaggableManager(through=TaggedProblem) class Meta: verbose_name = "problem" verbose_name_plural = "problems" def __str__(self): return self.title class Deck(models.Model): name = models.CharField(max_length=200) problems = models.ManyToManyField(Problem) def __str__(self): return self.name then for the admin i have the following from django.contrib import admin # Register your models here. from .models import Problem,Deck class DeckAdmin(admin.ModelAdmin): filter_horizontal = ('problems',) admin.site.register(Deck, DeckAdmin) admin.site.register(Problem) and the admin looks like this well what i want to do is to have a custom filter to filter the available problems, the filter must be an interface where i can include and exclude tags associated with the problems, so i want to replace the filter search box with something like this so i can filter the problems by tags and then add then to the deck, how can i achieve that functionality?, i am new to django and have no idea … -
CheckConstraint in Django model not triggering in unittest.TestCase (AssertionError: IntegrityError not raised)
I have a Model class with a series of constraints that I am attempting to test, and I am unable to get these constraints to return an IntegrityError in testing. The class is as follows: from django.db import models from django.db.models import CheckConstraint, Q, UniqueConstraint class Products(models.Model): sku = models.CharField(primary_key=True, max_length=8) barcode = models.CharField(unique=True, max_length=14, blank=True, null=True) name = models.TextField(blank=True, null=True) rrp = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) status = models.TextField() manufacturer = models.TextField(blank=True, null=True) brand = models.TextField(blank=True, null=True) country_of_origin = models.TextField(blank=True, null=True) last_updated = models.DateField(blank=True, null=True) date_published = models.DateField(blank=True, null=True) exclusive = models.BooleanField(blank=True, null=True) class Meta: managed = False db_table = 'product' constraints = [ CheckConstraint( condition=Q(status__in=['Draft', 'Live', 'Discontinued']), name='check_status', violation_error_message="status field must be on of the following: 'Draft', 'Live', 'Discontinued'", ), CheckConstraint( condition=~(Q(date_published__isnull=False) & Q(status__in=['Draft', 'Discontinued'])), name='check_date_published', violation_error_message="Product with status 'Draft' or 'Discontinued' cannot have a date_published value" ), UniqueConstraint(fields=['barcode'], name='unique_barcode'), UniqueConstraint(fields=['sku', 'exclusive'], name='unique_sku_and_exclusive'), UniqueConstraint(fields=['sku', 'status'], name='unique_sku_and_status') ] The 'managed' value is flipped in 0001_initial.py when tests are run. The IntegrityError I'm using is from django.db.utils and not sqlite3, however the save() method isn't returning any exceptions to begin with, so the issue is not coming from the wrong version of IntegrityError. from django.db.utils import IntegrityError from django.test import … -
Issue with connecting Mongodb Atlas with Django using Mongoengine
I have created cluster using free tier in Mongodb Atlas and also it connected with my current IP address. When I am running python manage.py runserver it gives me error-ServerSelectionTimeoutError at /. However if I change the IP address to 0.0.0.0/0 then it gets connected and showing the data in the browser. Kindly suggest me how to get successful connection? Following are the settings I have added in django application: .env file: MONGODB_NAME=db_name MONGODB_HOST=host MONGODB_USER=user MONGODB_PASSWORD=password Django settings.py: from dotenv import load_dotenv import mongoengine, os load_dotenv() MONGODB_NAME=quote_plus(os.environ.get('MONGODB_NAME')) MONGODB_HOST=quote_plus(os.environ.get('MONGODB_HOST')) MONGODB_USER = quote_plus(os.environ.get('MONGODB_USER')) MONGODB_PASSWORD = quote_plus(os.environ.get('MONGODB_PASSWORD')) atlas_uri = f"mongodb+srv://{MONGODB_USER}:{MONGODB_PASSWORD}@{MONGODB_HOST}/{MONGODB_NAME}?retryWrites=true&w=majority&appName=Cluster0" mongoengine.connect( db=MONGODB_NAME, host=atlas_uri, alias="default", tls=True ) -
How to make Django more secure? [closed]
I came across this package that helps with Django security. It feels really comprehensive while still being easy to use — not too complicated. Package: https://github.com/xo-aria/django-secux I gave django-secux a try in one of my test projects, and so far it looks solid. But I'm curious to know: Has anyone here used it in production? Do you think it's safe and trustworthy enough for real projects? -
Best way to use docker with Django. Containerize ?, or all in a container?
I've read some tutorials about docker and django : some guys "containerize" an existing app already installed locally. and others install Django in a docker-compose and a Dockerfile (using pip for example), with volumes indeed. So "nothing" is installed locally, all the app is in a container. Accessing directly the container. Why is the best way ? Have you some relevant example ? F. -
How can I securely encrypt spatial fields (GeoDjango / PostGIS) in Django?
I’m working on a Django project with GeoDjango models that store user location data (e.g., PointField, LineStringField). Because location data is highly sensitive, I want to ensure it’s secured (?encrypted) at rest in the database. The challenge is that most Django field encryption libraries (like django-cryptography) work well for standard CharField or TextField, but don’t appear to support spatial fields directly. My requirements are: I don’t need to run spatial queries in PostGIS (like ST_Contains, ST_Distance, etc., although it would be a bonus if I could maintain this functionality of GeoDjango) — I can handle geometry operations in Python (Shapely/GEOS) after decryption. I do want the raw data encrypted in the database so that DB admins can’t see exact coordinates. Ideally, I’d like to keep using Django’s model field API so that saving/retrieving encrypted geometries feels natural. Has anyone implemented a secure way to encrypt GeoDjango fields? Any examples or best practices would be greatly appreciated! -
Pytest-django database not rolled back with pytest-asyncio
For context, I am trying to test a WebSocket connection made through Django, so I need to set up some async tests with database support. To do so, I have set up pytest-django and I have some trouble understanding the django_db decorator's behavior in async contexts. django_db has a parameter transaction which defaults to False. With this setting, the test class is supposed to act as django.test.TestCase which runs all tests in a transaction which is rolled back at the end of the test. However, in an async context, the objects created within a test seem to persist in other tests. Setting @pytest.mark.django_db(transaction=True) does make the tests pass, but increases test duration as actual modifications are made to the database. Here are quick examples: import pytest from cameras.models import CameraGroup as MyObject @pytest.mark.django_db @pytest.mark.asyncio class TestAsync: async def test_1(self): # OK await MyObject.objects.acreate(name="same-name1") assert await MyObject.objects.acount() == 1 async def test_2(self): # FAILS # This should not see test_1's object if rollback worked assert await MyObject.objects.acount() == 0 @pytest.mark.django_db(transaction=True) @pytest.mark.asyncio class TestAsyncWithTransaction: async def test_1(self): # OK await MyObject.objects.acreate(name="same-name2") assert await MyObject.objects.acount() == 1 async def test_2(self): # OK # This should not see test_1's object if rollback worked assert … -
Displaying Categories using forloop in Django project not working
I am making an ecommerce website using Django, and for displaying categories as buttons in the navbar, I tried using a forloop, but its not working. {% for category in categorys %} <li class="nav-item"><a class="nav-link" href="#">{{ category.name }}</a></li> {% endfor %} I tried it with products and it worked. -
Docker django + host posfix gives `Bad destination mailbox address: Address not recognized by gateway`
I'm trying to persuade containerized django to send emails using the postfix installation on my host, and I'm told Bad destination mailbox address: Address not recognized by gateway. (For more detail, the django application I'm running is docker-zulip.) When I trigger a password-recovery email, I expect the email to be sent, but my server log in the container (/var/log/zulip/server.log) reports: 2025-09-01 22:47:00.280 ERR [zulip.send_email] Error sending password_reset email to ['User <user@gmail.com>' ]: {'User <user@gmail.com>': (550, b'5.1.1 Bad destination mailbox address: Address not recognized by gateway. ')} I'm aware of the SO post How do you configure Django to send mail through Postfix?, and I'm using its prescribed settings. But that post doesn't focus on docker setups, so it looks as if something further is required. Can the host send emails? Yes I can send emails from the host easily enough using echo "BODY" | mailx -r test@example.com -s "SUBJECT" user@gmail.com. Is postfix configured to recognize traffic from the container? I think so I've configured /etc/postfix/main.cf in a way that I think supports my docker container (running on 172.18.0.100): mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 172.18.0.0/24 inet_interfaces = 172.17.0.1 172.18.0.1 172.23.0.1 ...and I've run systemctl restart postfix. I don't see any activity … -
Nginx: “no ssl_certificate is defined for the listen … ssl directive” on custom port 8001
I’m running Django project behind Nginx on my VPS. Main project is at https://myproject.com (port 443) and works like a charm. I want to expose a second Django project at https://myproject.com:8001 but I couldn't load it on that address, I got the error mentioned in the title: no ssl_certificate is defined for the listen … ssl directive” on custom port 8001 For this, I updated /etc/nginx/sites-available/myproject to this (first part works fine for the main project at https://myproject.com, the second part is where I encounter some issues (marked with # NEW CONFIG FOR SECOND PROJECT (on :8001)): # Redirect all HTTP requests to HTTPS server { listen 80; server_name myproject.com www.myproject.com; return 301 https://$host$request_uri; } # Serve the app over HTTPS server { listen 443 ssl; server_name myproject.com www.myproject.com; ssl_certificate /etc/letsencrypt/live/myproject.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/myproject.com/privkey.pem; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/myname/myproject/staticfiles/; } location /media/ { alias /home/myname/myproject/media/; access_log off; expires 1h; } location / { include proxy_params; proxy_pass http://127.0.0.1:8000; } } ########################################## # NEW CONFIG FOR SECOND PROJECT (on :8001) # HTTP on :8001 → HTTPS on :8001 server { listen 8001; server_name myproject.com www.myproject.com; return 301 https://$host:8001$request_uri; } # HTTPS on :8001 for … -
How can I resolve this Django TemplateDoesNotExist error?
I'm working through the "Django 5 by Example" textbook, and am nearly finished with chapter 12, however at the very end when the text asks you to runserver and checkout http://127.0.0.1:8000/accounts/login, I get the following error: TemplateDoesNotExist at /accounts/login/ registration/login.html Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login/ Django Version: 5.2.5 Exception Type: TemplateDoesNotExist Exception Value: registration/login.html Exception Location: C:\Users\Zergy\python\django\django-learning\env\educa\Lib\site-packages\django\template\loader.py, line 47, in select_template Raised during: django.contrib.auth.views.LoginView Python Executable: C:\Users\Zergy\python\django\django-learning\env\educa\Scripts\python.exe Python Version: 3.13.1 Python Path: ['C:\Users\Zergy\python\django\django-learning\educa', 'C:\Users\Zergy\AppData\Local\Programs\Python\Python313\python313.zip', 'C:\Users\Zergy\AppData\Local\Programs\Python\Python313\DLLs', 'C:\Users\Zergy\AppData\Local\Programs\Python\Python313\Lib', 'C:\Users\Zergy\AppData\Local\Programs\Python\Python313', 'C:\Users\Zergy\python\django\django-learning\env\educa', 'C:\Users\Zergy\python\django\django-learning\env\educa\Lib\site-packages'] Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: C:\Users\Zergy\python\django\django-learning\env\educa\Lib\site-packages\django\contrib\admin\templates\registration\login.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Zergy\python\django\django-learning\env\educa\Lib\site-packages\django\contrib\auth\templates\registration\login.html (Source does not exist) I have checked, double-checked and triple-checked that my spelling and file structure are the same as what is given in the textbook, but the error persists. Here's the relevant parts of settings.py: INSTALLED_APPS = [ 'courses.apps.CoursesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ROOT_URLCONF = 'educa.urls' Here is the file structure Here is educa/urls.py from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('accounts/login/', auth_views.LoginView.as_view(), name='login'), path('accounts/logout/', auth_views.LogoutView.as_view(), name='logout'), path('admin/', admin.site.urls), ] if settings.DEBUG: urlpatterns += static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT … -
I have a Django model called DataLog that stores API action logs. I need to delete this automatically after every 60 days
What is the best practice in Django to achieve this? Should I use a management command + cron job, django-crontab, or Celery beat for scheduling the deletion? Is there a way to make this automatic without having to call the cleanup manually inside my views? I tried using crontab by creating a function to delete the data after 60 days from created_at. -
Catching an AI-Generated Bug in Django URL Handling
Recently, I was experimenting with Django URL customization and token-based encryption. I used AI "ChatGPT" to optimize code include these lines : url = url[1:] + req.request_token url = '/' + encrypt_text(url) + '/' But I spotted a subtle bug in the output. url = url.rstrip("/") # ❌ Wrong: strips slashes from the right url = "/" + url The issue: rstrip("/") removes trailing slashes from the end of the string, but Django URLs require a single leading slash at the start. This could accidentally produce malformed URLs such as: "//myview/12345/token/" 💡 Lesson learned: even with AI assistance and easy code hacking, you always need to review and validate code carefully. Small string operations can break URL patterns in Django. Using AI to optimize my code. -
Django enrich QuerySet
I have an Django Application that runs only locally on my machine. I have two diffrent tabels, with the transaction and the price. Now I want to enrich my transaction with the price. I wrote something similar already to calculate the average price: for transaction in transactions: filter_date = transaction.timestamp.date() price = Price.objects.filter(fiat=cur_id, date=filter_date).first() if not price: price = PriceTextBackup.objects.filter(fiat=cur_id, date=filter_date.strftime("%d-%m-%Y")).first() if price: if transaction.amount > 0: sats_price=price.price*transaction.amount price_list.append(sats_price) transaction_counter += transaction.amount I display the price in a popup on mouseover, the html page looks like this {% if transaction.amount >= 0 %} <td onmouseover="showPopup({{forloop.counter}}0000)" onmouseout="hidePopup()" class="text-success">{{transaction.fiat_CHF|floatformat:2 |intcomma }}</td> {% else %} <td class="text-danger">{{transaction.fiat_CHF|floatformat:2 |intcomma }}</td> {% endif %} How can I do the same logic for the price in the queryset? -
Websocket with Cloudflare proxy closes connection instantly with code 1006
What is the issue or error you’re encountering I have create a Django app which run on a uvicron server on and AWS EC2. The EC2 is attached to a load balancer which is then connected to cloudflare proxy. If I remove cloudflare proxy, websockets work fine, even with SSL/TLS enabled, https, etc. But as soon as I turn on cloudflare proxy (orange cloud), the websocket conneciton instantly close upon opeing. They give 1006 error code which means nothing. What steps have you taken to resolve the issue? I have looked at the logs, to see that the handshake is a successful. But when this reaches to the client, websocket disconnects, instanlty. app-be | INFO: ('172.18.0.7', 58718) - "WebSocket /ws/debug/" [accepted] app-be | INFO: connection open app-fe | 10.2.0.231 - - [31/Aug/2025:12:47:26 +0000] "GET /ws/debug/ HTTP/1.1" 101 0 "-" app-be | INFO: connection closed app-be | [django] [INFO] [2025-08-31 13:17:53,550] WebSocket disconnected: 1006 I have even sent a message just after connection, in the logs I can see a message has been sent, but client never receives it. I don’t know where do I go from here, I have: Websockets enabled on cloudflare I am sending a keep alive notification … -
Git is not making a conflict when I think it should be
I am learning how to deploy a django website and for that I have 2 copies of the code in 2 Git branches one for developing (master) and the other for deploying (deployment) with differint configuarations. I did some modification in master branch and want them to be availabe in deployment. I should have some conflicts because of the different configurations files like in settings.py there is debug=True in master and allowed hosts are empty, in the other hand it is False in deployment and allowed hosts are added. Git is not making any conflicts with these 2 lines so I am not able to choose which one I want when merging into deployment. side note: the modifications in git master branch that I want to bring to deployment should not do any conflicts. the conflicts I am waiting are just in already existed differences in the code (the purpose of having these 2 branches). -
what does shutil.rmtree(d, ignore_errors=True) do?
I was working with shutil module. My file structure looked like this projects/backend/--3-5 repos-- . In one of the repo's views.py I used for d in destDirs: shutil.rmtree(d, ignore_errors=True) destDirs = "projects/backend/repo1/static/file1 After that my whole file system got deleted. After running the API that had that code my whole file system got deleted. -
How to containerize a Django App properly?
I have sucessfully developed a Django App. However, i made some changes to the admin-panel and actually I can only successfully deploy the App in my tes-environment when I migrate the base-"makemgrations" and copy afterwards the changed migrations files for admin panel and so on and repeat the 'migrate' command afterwards. Reason is clear: in first migrate-command, there are no database fields to accept the changes i made. But how can I put this in a Docker-Containerized package for distributionwithout this issue? -
Django OneToOneField, Pyright: Cannot access attribute (reportAttributeAccessIssue)
I try to check my Django project with pyright. There is this OneToOneField, which pyright does not detect, when I use it: user.lala Error message of pyright: error: Cannot access attribute "lala" for class "User" Attribute "lala" is unknown (reportAttributeAccessIssue) # file lala/models.py class LaLaUser(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True, related_name="lala" ) discount = models.PositiveSmallIntegerField( default=0, verbose_name="Discount (0 bis 100)", validators=[MinValueValidator(0), MaxValueValidator(100)], ) def __str__(self): return self.user.username The django-stubs are installed, and all other Django magic works fine with pyright. Version: Django 5.2, pyright 1.1.404. How to make pyright understand that OneToOneField? (ignoring that via a comment is not an answer) -
How can use jwt and allauth. and is combing the neccessary?
I. Have been try to combine both jwt and django allauth but i'm still considering that is not important I have read different dicumentation but i was not still statified please i need some advice And is my allauth email-verfication is showing the Ip address of the site how can i make it to the site name -
Problem with setting default file storage to boto for s3 integration?
The default storage does'nt change! There by not letting me add images to the aws bucket and coz of that it shows an access denied message when i open the image url but in reality it just added the image to my local system so there is nothing in that url!! I built an ecom website using django and now i want to integrate aws s3 for being able to add the images via the admin pannel and it being stored in the aws bucket! I tired changing the default storage in the settings.py and even tried using gpt and after all that when i check the default file storage it keeps showing my local storage! and when i add an image via the admin page it just creates a folder called products locally and add the image there! Please help me fix this!! -
Django doesn't release database connections for re-use, long after request has finished
My django app loads several pages (images) at once, e.g. to show a document, and queries the database mainly to check permissions. Django keeps the connections alive, but doesn't re-use them. At some point the maximum number of connections of postgresql is reached, and will never be 'unreached' because of this behavior. I've added CONN_MAX_AGE of 15 seconds and intermediate pgbouncer, but the behavior is the same, the connections stay open, even after 15". { "default": { "ENGINE": "django.db.backends.postgresql", "HOST": "pgbouncer","PORT": 6432,"NAME": "...", "USER": "...", "PASSWORD": "...", "CONN_MAX_AGE": 15, "CONN_HEALTH_CHECKS": true } } The settings point to a pgbouncer proxy in this case, but I also have this issue without pgbouncer. Here's what I see. I've loaded a couple of pages on the website, and they fill up pg_stat_activity. SELECT split_part(query, 'WHERE', 2) AS sql, COUNT(*) AS count FROM pg_stat_activity WHERE datname = '...' GROUP BY query sql count ... "page"."page_id" = 12 ... 1 ... "page"."page_id" = 65 ... 1 ... "page"."page_id" = 23 ... 1 ... "page"."page_id" = 78 ... 1 ... "page"."page_id" = 32 ... 1 ... many more rows ... ... These entries stay, with exactly the same page_id, for hours, eventhough the development console of … -
Django-Tenant-Users: IntegrityError on permissions_usertenantpermissions_profile_id_key when creating a tenant
I’m using Django with django-tenants and django-tenant-users to manage multi-tenant accounts. I’m having an issue when creating a new tenant: When I try to create a new user + its tenant through my view, I get the following error: django.db.utils.IntegrityError: ERROR: Duplicate key value breaks unique constraint 'permissions_usertenantpermissions_profile_id_key' DETAIL: Key '(profile_id)=(8)' already exists. I even cleared the table and tried but with all that the error is there Here is the code for my school_login view: def school_login(request): if request.method == 'POST': form = CreateSchoolForm(request.POST) if form.is_valid(): sigle = form.cleaned_data['sigle'] slug = form.cleaned_data['sigle'].lower() email = form.cleaned_data['email'] password = form.cleaned_data['password'] # Create the user user = SchoolUser.objects.create_user( email=email, password=password, ) user.role = 'director' user.is_verified = True user.save() # Create the tenant tenant, domain = provision_tenant( tenant_name=sigle, tenant_slug=slug, owner=user, is_superuser=True, is_staff=True, ) # Authenticate and login authenticated_user = authenticate(request, username=email, password=password) if authenticated_user: login(request, authenticated_user) tenant_domain = get_tenant_domain_model().objects.get(tenant=tenant).domain return HttpResponseRedirect(f"http://{tenant_domain}/") else: form = CreateSchoolForm() return render(request, 'school_login.html', {'form': form}) Here is the code of models.py in the shared app: class SchoolUser(UserProfile): ROLE_CHOICES = ( ('director', 'Directeur'), ('accountant', 'Comptable'), ) role = models.CharField(max_length=20, choices=ROLE_CHOICES, default='accountant') def is_director(self): return self.role == 'director' def is_accountant(self): return self.role == 'accountant' class School(TenantBase): name = models.CharField(max_length=100) # …