Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Chaining filter with django filter and django autocomplete light
I am trying to combine Django Filters (DF) with Django Autocomplete Light (DAL). I also want to chain the filter on a few fields in my model. For instance, before applying the DF to my model, I'd like to accomplish the following: Select a certain country. Filter all regions within the selected country. Filter all the cities within the selected region. I have implemented DF and DAL separately and have no issues, which indicates that my views are working as intended. Therefor I don't see any point to share the URLs. I can the see the following response in the console when manually testing DAL in another form: This means that the forwarding in DAL works. However, when I try DF together with DAL: I see that the dictionary values are not set. Which is correct because in the drop-down form I don't see any filtering. I can only auto complete my search for the country field. The region and city fields are not working properly. Views: class CountryAutoComplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Country.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs class RegionAutoComplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Region.objects.all() country = self.forwarded.get("country", None) if country: qs = qs.filter(country=country) if self.q: qs … -
Django translation for uz-cyrl return uz instead
I have configured my django LANGUAGES like import os from django.utils.translation import gettext_lazy as \_ from config.settings.base import BASE_DIR LANGUAGE_CODE = "en" USE_I18N = True LANGUAGES = ( ("uz", _("Uzbek")), ("uz-cyrl", _("Cyrillic")), ("ru", _("Russian")), ("en", _("English")), ("ar", _("Arabic")), ) LOCALE_PATHS = [os.path.join(BASE_DIR, "locale")] I have translated texts in all .po files and compiled them. In local runserver it works with Accept-Language: uz-cyrl properly, but through docker-compose it returns uz translation instead, what might be the reason? I have used different base docker images like python3.11-slim, python3.11 itself but not worked. -
How to Migrate from LDAP to LDAPS in a Django Application?
I'm currently using Django with django-auth-ldap for authentication, and my organization is transitioning from LDAP to LDAPS for security reasons. I need to update my Django settings to use LDAPS instead of LDAP, but I'm unsure of the exact steps required. Here’s my current configuration: AUTH_LDAP_SERVER_URI = "ldap://abc.example.com" AUTH_LDAP_BIND_DN = "cn=admin,dc=example,dc=com" AUTH_LDAP_BIND_PASSWORD = "password" AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=users,dc=example,dc=com", ldap.SCOPE_SUBTREE, "(uid=%(user)s)") I understand that for LDAPS, I need to change AUTH_LDAP_SERVER_URI to ldaps://abc.example.com:636, but I have a few questions: What other changes are required in Django settings? Do I need to configure SSL certificates for django-auth-ldap to work with LDAPS? If so, how? -
VSCode Ignores Mypy Type Hints When Using Django Plugins
I'm using VSCode and mypy in my Django project. My pyproject.toml configuration looks like this (following the Django Stubs README): [tool.mypy] mypy_path = "." python_version = "3.13" strict = true plugins = ["mypy_django_plugin.main"] [tool.django-stubs] django_settings_module = "conf.settings" When I run mypy in the terminal, everything works fine, and I get proper type checking. However, in VSCode, I don't get any type hints at all. If I comment out the plugins line, mypy starts working in VSCode again. What I've Tried: Running mypy manually in the terminal → Works as expected Commenting out plugins → VSCode starts showing hints again Checking that VSCode uses the correct mypy config (it's picking up pyproject.toml) Any insights would be greatly appreciated! -
ANPR OpenCV PyTesseract Python Code not working
Crappy coder needs help with code. Began work on a Python Script for an Automated License Plate Recognition system on a Raspberry Pi. The intended goal of it is to derive a plate from an image, read the text and download to a file. The text is then displayed on a HTML webpage connected via Django Framework. I've been told to change from PyTesseract to a different OCR model but I'm too far into the project to really change anything substantially. I'm not sure what's going wrong specifically with the code so any input is appreciated. import cv2 import pytesseract import os import datetime import numpy as np # Directory to save images IMAGE_DIR = "captured_plates" if not os.path.exists(IMAGE_DIR): os.makedirs(IMAGE_DIR) # File paths ARRIVED_FILE = "arrived.txt" LEFT_FILE = "left.txt" # Open the camera cap = cv2.VideoCapture(0) def preprocess_image(image): """Convert image to grayscale, blur, and apply adaptive thresholding.""" gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(gray, (5, 5), 0) edged = cv2.Canny(blurred, 100, 200) # Edge detection return edged def find_license_plate(image): """Detect contours and extract the region most likely to be the license plate.""" processed = preprocess_image(image) contours, _ = cv2.findContours(processed, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) possible_plates = [] for contour in contours: x, y, … -
no such column: polls_question.question_text?
Step:1 Use THis Command python manage.py dbshell If you're using SQLite, you can use the dbshell to interact directly with the database and check if the column question_text exists in the polls_question table. If it doesn't exist, there was likely an issue with the migration. Step:2 Then, in the shell, you can run the following query: PRAGMA table_info(polls_question); This will list all the columns in the polls_question table, and you can check if question_text is listed. Step:3 If the column is not there: If the question_text column is not visible, it means that your migration has not been applied correctly, or for some reason, the database has not been updated properly. In this case, you will need to run the migration again, as mentioned earlier. You need to run python manage.py makemigrations and python manage.py migrate to update the database. Step:4 Run the Application After Fixes Once you’ve confirmed that the migration has been applied correctly and the model matches the database, try accessing your application again and check if the error persists. What I tried in my previous explanation was to provide a step-by-step guide on how to troubleshoot the issue with the polls_question.question_text column not being found in … -
xml UBL2.1 invoice error python , using django block template
I got this error when i tried to check validity of xml invoice Error in an electronic invoice in UBL (Universal Business Language) format that relates to compliance with billing requirements, so here I'm using django block template that function call to create xml files from invoices depending on ubl 2.1 , i got error when I'm trying to check validity of xml invoice ... could any one help here is the code of the template {% comment %} {% for discount in %} {% endcomment %} {% if invoice.allowance_discount %} <cac:AllowanceCharge> <cbc:ID>1</cbc:ID> <cbc:ChargeIndicator>false</cbc:ChargeIndicator> <cbc:AllowanceChargeReason>discount</cbc:AllowanceChargeReason> <cbc:Amount currencyID="{{ invoice.currency.code }}">{{ invoice.allowance_discount|default:"0.0"|floatformat:2 }}</cbc:Amount> <cac:TaxCategory> <cbc:ID schemeAgencyID="6" schemeID="UN/ECE 5305">{{ invoice.company.finance_company.account_sale_tax.vat_category_code }}</cbc:ID> <cbc:Percent>{{ invoice.company.finance_company.account_sale_tax.amount|default:"0.0"|floatformat:2 }}</cbc:Percent> <cac:TaxScheme> <cbc:ID schemeAgencyID="6" schemeID="UN/ECE 5153">VAT</cbc:ID> </cac:TaxScheme> </cac:TaxCategory> </cac:AllowanceCharge> {% endif %} {% comment %} {% endfor %} {% endcomment %}` ``` here is the error and warning i got `Errors category : BR_ERROR code :BR-CL-18 message : Invoice tax categories MUST be coded using UNCL5305 code list Warnings category : BR_KSA_WARNING code :BR-KSA-80 message : The Pre-Paid amount (BT-113) must be equal to the sum total of the Prepayment VAT category Taxable Amount (KSA-31) and the Prepayment VAT Category Tax Amount (KSA-32). category : BR_KSA_WARNING code :BR-KSA-08 message : … -
Database not connecting
I have tried different databases with my Django projects but it's not connecting.The railway connection is showing " could not translate host name"postgress.railway.internal"" While the supabase is showing same thing. No such host is known I have made sure the credentials are correct expecting the tables to be created once I do my migration but it doesn't -
django-allauth: enforce policies for certain users
I'm looking to implement django-allauth for an existing project, mainly to add OTP and SSO. I have an SPA so I would need the allauth API as documented here. However, since this requires quite a lot of refactoring I'm a bit hesitant to just throw this app in there, and I can't really tell if it's possible to do what I want from just the documentation. Depending on the Organization a user belongs to (or is invited to), there might be different requirements. I need to be able to enforce OTP or SSO (from a specific provider), but only for certain users. This applies to both existing and new users. Example flows: New user is invited to an organization with OTP enforcement User signs up User accepts invite User is forced to setup OTP because of organization policy New user is invited to an organization with SSO enforcement Because of SSO, user can only sign up with specific SSO An organization adds the enforcement of OTP for their users Any existing organization user that logs in will have to setup OTP before continuing Existing user is invited to organization with policy User logs in User accepts invite User is forced … -
I encountered an AUTH_USER_MODEL error while trying to populate my database with fake data?
I wanted to populate my database for testing purposes, so after doing some research, I came across a tool called FactoryBoy. I decided to use it in conjunction with Pandas to extract data from a CSV file and load it into my database. After writing the code, I gave it a try. Initially, I faced some configuration issues, particularly with defining the correct path, as I was running the script directly without using manage.py. Eventually, I encountered an error that I couldn’t resolve, as I couldn't define the source. django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'users.User' that has not been installed I added the users module to the INSTALLED_APPS environment variable, but I'm still encountering this error. Do you have any suggestions on how to fix it? -
Django : 'empty_form' is not used in polymorphic formsets, use 'empty_forms' instead
I am newbie at Python/Django i have been charged to migrate old project from Python 3.7 / Django 2.2.5 to the Python 3.12 and Django 5.1 but when i did this some functionality didn't work now . For exemple before i have in the Admin interface when i click on "Add watcher" i can create watcher and in the same page choose the realted Trigger, Indicator and other staff. But in my new version when i choose Add Watcher i have this error : RuntimeError at /admin/watchers/watcher/add/ 'empty_form' is not used in polymorphic formsets, use 'empty_forms' instead. I am using the last version of django-polymorphic, nested-admin , I know that django-polymorphic is listed as only supporting Django versions 2.2, 3.0, 3.1, 3.2 and 4.0. It does not support Django version 5.1 , I tried the a later version using pip install git+https://github.com/jazzband/django-polymorphic.git@v4.0.0a#egg=django-polymorphic and also Django 4.x i got the same error: from polymorphic.admin import PolymorphicParentModelAdmin, PolymorphicChildModelAdmin, PolymorphicInlineSupportMixin import nested_admin from django.db import transaction from watchers.models import * class TriggerInline(nested_admin.NestedStackedPolymorphicInline): model = apps.get_model('triggers', 'Trigger') child_inlines = tuple([type(f'{subclass.__name__}Inline', (nested_admin.NestedStackedPolymorphicInline.Child,), { 'model': subclass, 'inlines': [ TriggerComponentInline] if subclass.__name__ == "CompositeTrigger" else [] }) for subclass in apps.get_model('triggers', 'Trigger').__subclasses__()]) #Same that TriggerInline class IndicatorInline(nested_admin.NestedStackedPolymorphicInline) … -
Django TemplateDoesNotExist error for Jinja2 template (dashboard.jinja)
I'm trying to use Jinja2 templates in my Django project, but I'm getting the following error when accessing the / (dashboard) page: TemplateDoesNotExist at / dashboard.jinja My Setup: Settings (app/settings.py) I have configured Jinja2 as the template backend: TEMPLATES = [ { 'BACKEND': 'django.template.backends.jinja2.Jinja2', "DIRS": [BASE_DIR / "core/templates"], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Template Location (app/authentication/templates/dashboard.jinja) {% extends 'core/layouts/main.html' %} {% block title %}Dashboard | {% endblock %} {% block content %} <h2>Welcome, {{ user.name }}</h2> <a href="{% url 'logout' %}">Logout</a> {% endblock %} View (app/authentication/views.py) @login_required def dashboard(request): return render(request, "dashboard.jinja", {"user": request.user}) Issue: The file dashboard.jinja exists in app/authentication/templates/, but Django is unable to find it. I'm not sure if my TEMPLATES settings are correct for Jinja2. I expected render(request, "dashboard.jinja") to find the file, but it throws TemplateDoesNotExist. What I’ve Tried: Ensured the file exists in app/authentication/templates/. Checked that the TEMPLATES["DIRS"] path is correct (core/templates). Tried moving dashboard.jinja to core/templates/ to see if it gets detected. Question: How can I correctly configure Django to find my Jinja2 template inside app/authentication/templates/? Do I need to modify TEMPLATES['DIRS'], or should I use a different approach? Any help would be appreciated! -
How to conditionally modify the <title> tag in Django templates?
I have a base template (main.html) with the following code for the tag: main.html: <title>{% block title %}{% endblock %} | Application</title> In a child template (dashboard.html), I override the title block like this: dashboard.html: {% extends 'main.html' %} {% block title %}Dashboard{% endblock %} If the title block is not overridden in the child template, I want the title to just be Application, without the extra | Application. How can I check if the block is overridden and modify the title accordingly? When I pass the title block from the child template like this: {% extends 'main.html' %} {% block title %}Dashboard{% endblock %} Then I need the title to display as "Dashboard | Application". If I don't pass the title block: {% extends 'main.html' %} Then the title should just be "Application". -
How to check if a Django template block is overridden in the child template?
I am working on a Django project where I have a base layout template (main.html) and a child template (dashboard.html). I want to modify the tag so that if the child template provides a title, it should be formatted as: Page Title | Application Otherwise, if the block is empty or not overridden, it should just be: Application (without the extra | Application). Here’s my main.html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> {% block title %}{% endblock %}{% if block.super %} | Application{% endif %} </title> <link rel="stylesheet" href="{% static 'assets/css/style.css' %}"> </head> <body> {% block content %}{% endblock %} </body> </html> And here’s my dashboard.html: {% extends 'core/layouts/main.html' %} {% block title %}Dashboard{% endblock %} {% block content %} <h2>Welcome, {{ user.name }}</h2> <a href="{% url 'logout' %}">Logout</a> {% endblock %} Issue: When the child template doesn't override the title block, the output is: | Application Instead of just: Application How can I check whether a block is overridden in the child template and adjust the title accordingly? Would appreciate any suggestions. Thanks! -
Filter a combined queryset in Django Rest Framework
I created a viewset that combines different models that inherit from the same parent model (Transactions). It was working well and I could reach the endpoint. Now I am trying to add filters using django-filters, but I am getting an error: model = queryset.model AttributeError: 'list' object has no attribute 'model' The fields that I am using to filter and search belong to the parent model. Here is my viewset: class TransactionViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = TransactionSerializer filter_backends = [DjangoFilterBackend, filters.SearchFilter] filterset_fields = { "company": ["exact"], } search_fields = ["id", "description"] def get_queryset(self): payment_collections = PaymentCollection.objects.all() up_front_sales = UpFrontSale.objects.all() combined_queryset = list( chain( payment_collections, up_front_sales, ) ) return combined_queryset I see that the error is that my method returns a list instead of a queryset, but I tried to use the union method instead and got raise NotSupportedError( django.db.utils.NotSupportedError: Calling QuerySet.filter() after union() is not supported. Is there a way to use the default filterset_fields and search_fields with a combined queryset? -
NameError: name '_mysql' is not defined Mac Django
I was trying to run python manage.py run server while working with Django after changing my settings.py from this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } to this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'storefront', } } But I was getting this error: File "/Users/aditi/.local/share/virtualenvs/storefront-4vgosAeV/lib/python3.12/site-packages/django/db/backends/mysql/base.py", line 16, in <module> import MySQLdb as Database File "/Users/aditi/.local/share/virtualenvs/storefront-4vgosAeV/lib/python3.12/site-packages/MySQLdb/__init__.py", line 24, in <module> version_info, _mysql.version_info, _mysql.__file__ ^^^^^^ NameError: name '_mysql' is not defined This is what my __init__.py looks like: try: from MySQLdb.release import version_info from . import _mysql assert version_info == _mysql.version_info except Exception: raise ImportError( "this is MySQLdb version {}, but _mysql is version {!r}\n_mysql: {!r}".format( version_info, _mysql.version_info, _mysql.__file__ ) ) I downloaded MySQL from this link, the x86 DMG option: https://dev.mysql.com/downloads/mysql/ I have Sonoma 14.3. I am running Python 3.12.7. Please let me know how I can fix this error. I tried adding this to my .zshrc file: export PATH="/usr/local/mysql/bin:$PATH" But it did not work. -
Configuring Azure AD authentication for django Local development
I am using Azure AD for authenticating access to my django application and it works fine in the DEV environement. The application is in a container reached in this url: "https://application-dev.organization.org" Azure was configured and the redirect url was provided : "https://application-dev.organization.org/auth/complete/azuread-oauth2/ I have the same application in my local environment http://application.local:8080 I would like to add Azure AD authentication to it to be able to development locall before releasing to DEV and then TEST and PROD. How to configure a local application in AZURE AD. how will the redirect work ? is there some DNS work to be done. or does Azure traceback the TCP/IP link? I tried to configure Azure AD with my local enviroment by local admin does not have a clue -
Tracing the cause of drf_spectacular.plumbing.UnableToProceedError
I have inherited a Django app in which DRF Spectacular was never fully installed. I want to get it working so I can easily see how the API has been set up. There are quite a few models and serializers, and I suspect a custom field may be the cause of this error I am getting: drf_spectacular.plumbing.UnableToProceedError There is a stack trace pointing to drf_spectacular/plumbing.py but all that tells me is that a field type hint was not able to be generated, not which field or modal or whatever caused it. In the Spectacular settings, I have debugging set up: SPECTACULAR_SETTINGS = { 'DEBUG': True, ... How else can I tell what actually went wrong? I am trying to generate the schema inside a docker container with this command: docker compose run --rm site python manage.py spectacular --color --file schema.yml -
How to list updated records in Django forms?
I have 3 child tables that all relate to a parent table via foreign key relationships. I created a form to add records to this parent table that also has these foreign key relationships. The form queries these children and show the querySet object with N records in each object. Thus, I took this approach to populating the fields as multi-choice: # Form class CreateMatch(forms.ModelForm): p_choices = [(player.id, player.gamer_tag) for player in Players.objects.all()] e_choices = [(event.id, event.name) for event in Events.objects.all()] g_choices = [(game.id, game.name) for game in Games.objects.all()] player_one = forms.ChoiceField(choices=p_choices) player_two = forms.ChoiceField(choices=p_choices) game = forms.ChoiceField(choices=g_choices) event = forms.ChoiceField(choices=e_choices) class Meta: model = Matches fields = ['player_one', 'player_two', 'player_one_score', 'player_two_score', 'game', 'event', 'round', 'losers'] This will ensure fields like player_one populates all human readable names in the form field as a dropdown. # View from .forms import CreateMatch def add_match(request): context = { "title": "Add New Event" } if request.method == 'POST': form = CreateMatch(request.POST) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('add match') # Replace 'forum_home' with your actual URL name else: form = CreateMatch() return render(request, 'add_match.html', {'form': form, 'context': context}) # Parent model class Matches(models.Model): player_one = models.ForeignKey(Players, on_delete=models.CASCADE, related_name='%(class)s_player_one') player_two = models.ForeignKey(Players, on_delete=models.CASCADE, related_name='%(class)s_player_two') … -
How to properly serve static files through nginx in my django project
I've tried all possible configurations, but I don't know why nginx doesn't provide the static files for my application, that is, I always have a page without style. This is my Dockerfile: enter image description here This is my entrypoint.sh enter image description here This is my static configuration on settings.py enter image description here This is my docker-compose.yml enter image description here I have a folder in the root of my project called nginx. Inside it I have the files: Dockerfile enter image description here default.conf enter image description here I would like to understand what I'm doing wrong, I've tried other configuration structures, but nginx never serves the static files. -
When trying to authenticate user, Django presents a dropdown form of logins to update
I'm trying to code a password reset feature for a site, where the user enters their old password and new password. If the old password matches, the user's password is updated to the new password. However, I am having an error where a dropdown form asks which user I would like to update.Image of dropdown form I have no clue where the error is from. Here's a picture: The dropdown list always has the same users, even though I've created a lot more. I've tried a bunch of different ways to code a password reset view/form. I was expecting the issue to be within user authentication, but it seems to be deeper than that. -
urlpattern with arbitrary number of optional filters
In order to reflect filters in the URL, I need urlpatterns to include an arbitrary number of optional parameters, e.g.: /myview/filter1:option1/filter1:option2/filter2:option1/filter3:option5 Each filter can (potentially, depending on the type of filter) have multiple selected options, and multiple filters can be applied at one time. See MobyGames as an example of exactly what I mean. I imagine I need regex to achieve this, but I don't really know where to start. I read through the relevant docs, but didn't find anything that directly addresses this kind of pattern. -
Unable to Redirect to Next Page After Successful Login in Django
Despite entering the correct credentials, I am consistently redirected back to the login page instead of being granted access to the Products page. This issue persists even though the credentials are valid, which suggests that there might be a problem with the login and authentication process. As a result, I am unable to proceed beyond the login page. Views.py from django.shortcuts import render, redirect from django.http import HttpResponseRedirect, Http404 from .forms import UserRegisterForm, UserLoginForm,Reviews_Form from django.contrib import messages from .models import UserRegister, Review from django.contrib.auth import authenticate, login ,logout from django.contrib.auth.decorators import login_required from urllib.parse import urlparse from django.urls import is_valid_path # Create your views here. products = [ { "slug": "Mustang-GT", "About": """The Ford Mustang GT in its stunning white color is nothing short of a modern-day classic. From the moment you lay eyes on it, the Mustang's sleek and muscular design commands attention and admiration. The pristine white finish only adds to its allure, giving it a timeless, elegant look that stands out on the road. Performance: Under the hood, the Mustang GT roars to life with its 5.0-liter V8 engine, delivering a thrilling 450 horsepower. The acceleration is exhilarating, and the handling is precise, making every drive … -
Is it possible to render a column for each of a many-to-many relationship with django-tables2?
It's simple enough to get all the many-to-many relationships of a particular row - but they're rendered in the same column. Is it possible to have a column created for each one? For example, with a many-to-many relationship between Child and Year, and data for each child/year pair, I'd want a column for each Year in the table: Child 1998 1999 2000 ---------------------------- Eldest 155 162 170 Youngest 53 61 72 Middlest 80 91 103 (many to many in django-tables2 is the closest I've seen to a question about this, and I think the accepted answer is wrong; it doesn't render a column for each relationship at all.) -
NoReverseMatch: Reverse for 'chat_chatroom_changelist' not found. 'chat_chatroom_changelist' is not a valid view function or pattern name
Im triyng to register model in django admin, but i get error backend-1 | Couldnt reverse admin:chat_chatroom_changelist. Im using jazzmin for customize admin panel, and i setting up it for model JAZZMIN_SETTINGS { 'name':_('Chat'), 'model': 'chat.ChatRoom', 'url': 'admin:chat_chatroom_changelist', 'permissions': ['auth.view_user'], }, Model has been register in admin.py @admin.register(ChatRoom) class ChatRoomAdmin(admin.ModelAdmin): fieldsets = ( (None, {'fields': ('first_user', 'second_user')}), (_('Important dates'), {'fields': ('created_at', 'updated_at')}), ) list_display = ('id', 'first_user', 'second_user', 'created_at', 'updated_at') readonly_fields = ('created_at', 'updated_at') list_display_links = ('id', 'first_user', 'second_user') show_full_result_count = False def get_queryset(self, request): return super().get_queryset(request).select_related('first_user', 'second_user').order_by('-created_at') def get_history_queryset(self, request, history_manager, pk_name: str, object_id): qs = super().get_history_queryset(request, history_manager, pk_name, object_id) return qs.prefetch_related('history_user') model class ChatRoom(TimestampMixin, models.Model): first_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='first_user') second_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='second_user') def __str__(self): return ' / '.join([str(self.first_user), str(self.second_user)]) class Meta: db_table = 'chatrooms' app_label = 'chat' Project structure _|apps __|chat ___|admin ____|admin.py ___|models ____|chat.py ___|url.py ___|... __|... __|asgi.py __|wsgi.py _|settings __|main.py __|base.py __|jazzmin.py _|...