Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pycharm Django Run Error: CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False
When I start application I get following error: CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False How can I solve the problem? I want the program run with settings that I provided in settings.py file. -
How do I inspect objects passed to a custom save_model form in Django?
I'm working on overwriting a django save_model function, I want to do some debugging on the objects that get passed to it i.e. self, request: str, obj: ModelName, form: forms.ModelForm, change: str . Is it possible to "catch" those so I can play around with them in the shell? I've been printing and looking at them in the docker logs -
django deployment on aws elastic beanstalk
i have been struggling to deploy my django application on elastic beanstalk even after trying for many hours (i am using amazon linux 2, i dont know how to check this, but i am quite sure as i remember that this was the default setting when creating the elastic beanstalk application). i keep getting the following error: Mar 20 14:17:51 ip-10-0-2-193 web: ModuleNotFoundError: No module named 'gb_backend.wsgi' Mar 20 14:17:51 ip-10-0-2-193 web: [2023-03-20 14:17:51 +0000] [8829] [INFO] Worker exiting (pid: 8829) Mar 20 14:17:51 ip-10-0-2-193 web: [2023-03-20 14:17:51 +0000] [8823] [INFO] Shutting down: Master Mar 20 14:17:51 ip-10-0-2-193 web: [2023-03-20 14:17:51 +0000] [8823] [INFO] Reason: Worker failed to boot. Mar 20 14:17:52 ip-10-0-2-193 web: [2023-03-20 14:17:52 +0000] [8834] [INFO] Starting gunicorn 20.1.0 Mar 20 14:17:52 ip-10-0-2-193 web: [2023-03-20 14:17:52 +0000] [8834] [INFO] Listening at: http://127.0.0.1:8000 (8834) Mar 20 14:17:52 ip-10-0-2-193 web: [2023-03-20 14:17:52 +0000] [8834] [INFO] Using worker: gthread Mar 20 14:17:52 ip-10-0-2-193 web: [2023-03-20 14:17:52 +0000] [8840] [INFO] Booting worker with pid: 8840 Mar 20 14:17:52 ip-10-0-2-193 web: [2023-03-20 14:17:52 +0000] [8840] [ERROR] Exception in worker process Mar 20 14:17:52 ip-10-0-2-193 web: Traceback (most recent call last): Mar 20 14:17:52 ip-10-0-2-193 web: File "/var/app/venv/staging-LQM1lest/lib64/python3.8/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker Mar … -
Hardware requirements for Django server [closed]
What are the CPU and RAM recommended requirements for a Django server. It will have 200k transactions per day and 100 users, it will send requests to a database server. The database server is separate. I am asking only for the Django server. I am considering using 2gb RAM and 2.0 GHZ dual core. Would this be enough? -
d3js pan and zoom working with Five server test, but not with django runserver test
I made a test version of my code to use five server in vscode. I have managed to get pan and zoom to work via this example. I have moved all the javascript code changes to my django code set. However when I run this locally using the python manage.py runserver, the changes do not seem to have taken affect. As if I changed nothing in the code. I have tried clearing cookies and cache but that does not seem to make any difference. Here is the five server version: index.html: <!DOCTYPE html> <html> <head> <title>Tree</title> <link rel="stylesheet" href="static/css/style.css"> </head> <body> <script src="https://d3js.org/d3.v7.min.js"></script> <div id="plot"> </div> <script src="static/script.js"></script> </body> </html> script.js: d3.json("data/data_science.json").then(function(data) { console.log(data); // Set the dimensions and margins of the diagram // var margin = {top: 450, right: 90, bottom: 650, left: 275}, width = screen.width - margin.left - margin.right, height = screen.height - margin.top - margin.bottom; // append the svg object to the body of the page // appends a 'group' element to 'svg' // moves the 'group' element to the top left margin var i = 0, duration = 750, root; // declares a tree layout and assigns the size var treemap = d3.tree().size([height, width]).nodeSize([50, 40]); … -
How to retrieve value from dictionary with dynamic key in Django Template
I need to fetch and display the the value from dictionary using dynamic key in Django template. Model: class StatusData(models.Model): app= models.CharField(max_length=35) status= models.CharField(max_length=3) //possible values - SNY,DVL,TST class Meta: managed = False def __str__(self): return self.status view.py all_choices = {'SNY':'Sanity', 'DVL':'Develop', 'TST':'Testing'} model = StatusData.objects.order_by('-app') context = { "choices": all_choices, "modelData": model, } Django template: <html> {% for model%} <table> <tr> <td>{{ model.id }}</td> <td>{{ choices.model.status }}</td> // -- problem line </tr> </table> {% endfor %} </html> If I hardcode any specific key like {{ choices.SNY }} - it's deriving the the value as expected. How can I fetch the value by using the dynamic key that is returned by model.status i.e., {{ choices.model.status }}? -
how to run system commands inside a linux container or specify in Dockerfile?
I have created a Dockerfile for Djnago application and i want to run using a "gunicorn.service" file which have copied inside a /etc/systemd/system folder of an ubuntu container and i want to enable that Gunicorn service, but while using system or systemctl command it is showing command not found . what should do ? Expecting a Gunicorn automatically running in a background . -
How to refer to an inherited model in django
As in the title, that is, how to refer to an inherited model in django. I'm struggling with using the model_name function which returns the model name but it's not going the way I'd like. models.py class Product(PolymorphicModel): title = models.CharField(max_length=100, blank=True) image = models.ImageField(upload_to='product', default=None) quantity = models.IntegerField(null=False) is_available = models.BooleanField(default=True, null=False) price = models.IntegerField(null=False, blank=False, default=15) popularity = models.IntegerField(default=0) def __str__(self): return str(self.title) def get_absolute_url(self): return reverse("ProductDetail", args=[str(self.pk)]) @property def model_name(self): return self._meta.model_name class CD(Product): GENRE_CHOICES = ( ('Disco', 'Disco'), ('Electronic music', 'Electronic music'), ('Rap', 'Rap'), ('Reggae', 'Reggae'), ('Rock', 'Rock'), ('Pop', 'Pop'), ) band = models.CharField(max_length=100, null=False, blank=False) tracklist = models.TextField(max_length=500, null=False, blank=False) genre = models.CharField(max_length=100, choices=GENRE_CHOICES, null=False, blank=False) class Book(Product): GENRE_CHOICES = ( ('Biography', 'Biography'), ('Criminal', 'Criminal'), ('Fantasy', 'Fantasy'), ('Historical Novel', 'Historical Novel'), ('Horror', 'Horror'), ('Romance', 'Romance'), ('Sci-Fi', 'Sci-Fi'), ) author = models.CharField(max_length=100, null=False, blank=False) isbn = models.CharField(max_length=100, null=False, blank=False, unique=True) genre = models.CharField(max_length=100, choices=GENRE_CHOICES, null=False, blank=False) class Film(Product): GENRE_CHOICES = ( ('Adventure', 'Adventure'), ('Animated', 'Animated'), ('Comedy', 'Comedy'), ('Horror', 'Horror'), ('Thriller', 'Thriller'), ('Romance', 'Romance'), ) director = models.CharField(max_length=100, null=False, blank=False) duration = models.IntegerField(null=False, blank=False) genre = models.CharField(max_length=100, choices=GENRE_CHOICES, null=False, blank=False) views.py class Statistics(ListView): model = Product template_name = 'orders/statistics.html' def get_queryset(self): qs = super(Statistics, self).get_queryset() if self.request.GET: … -
using gunicorn in django xhtml2pdf doesn't render the images on pdf
using gunicorn for a program that must run on the local network when I request the pdf the images do not appear. In the home site, the css and images all appear, but the image does not appear when you request the pdf. I noticed that when loading the pdf, if I put the absolute path "http://localhost:8080/static/media/img.jpg in the html, it doesn't really resolve the request. I tried entering various solutions in the html image src, but it didn't solve the problem. I entered both {{ STATIC_ROOT }} from reading other solutions, and also tried {%static%} but the image is still not displayed. -
How to add a new field to the default user model in Django?
I want to add a new field to default Django user. I created a AbstractUser inherited model and added to the settings.py but I getting this error: ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'fdaconfig.customuser', but app 'fdaconfig' doesn't provide model 'customuser'. The field fdaconfig.Dataset.user was declared with a lazy reference to 'fdaconfig.customuser', but app 'fdaconfig' doesn't provide model 'customuser'. models.py class CustomUser(AbstractUser): user_info = models.CharField(max_length=255) settings.py AUTH_USER_MODEL = 'fdaconfig.customuser' -
Correct way to use a local Django project in a new computer (VS Code)
I created my first local Python/Django project a few months ago using Visual Studio Code. It worked perfectly. Now I'm trying to use it on a new computer. I've tried just saving the VS workspace and then loading it on the new computer, but it gives me the following error: ModuleNotFoundError: No module named 'gad' I think it's coming from the line os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'gad.settings') in manage.py I don't know if I should create a Django project from scratch and then copy my "old" files into that project, if I just have to create the "gad.settings" file or what. I don't have the old computer, but I think I have all the files from my old Django project (but there is no gad.settings file in it, so maybe I had to copy more files outside that folder). Thanks! -
How to validate JSON from API via serializer
I'm new in Django anf I know how to use model serializers, but I can't find information about how to validate data from API. For example, I have a method that gets a data from another web service. def get_sales(self): url = "https://statistics-api.com/api/v1/sales" body = {"dateFrom": f"{datetime.datetime.now().date() - datetime.timedelta(days=30)}"} try: request = requests.get(url, params=body) if request.status_code == 200: return True, request.json() return False, request.json()["errors"] except json.JSONDecodeError as e: return False, f"Response is not in JSON format" The response is in JSON format. Smth like this: (True, [{'date': '2023-03-03T13:02:22', 'barcode': '46134548641', 'totalPrice': 500, 'discountPercent': 52}] So, I need to get the data from response in my views.py: sales = api.get_sales() result, sales_info = sales if result: try: prices_count = [] for element in sales_info: price = element.get("totalPrice", "") prices_count.append(price) transactions_total = sum(prices_count) I know this is not the best practice, because of KeyError. How can I validate data via serializer? -
Connection closed before receiving a handshake response daphne+Gunicorn in docker
So im trying to set up project where websocket connection will be handled by daphne, and all the other things with gunicorn. Also i have nginx installed. When im assessing webpage where should be connected to websocket - websocket returns 200, and message (index):16 WebSocket connection to 'ws://localhost:9000/application/ws/endpoint/' failed: Connection closed before receiving a handshake response. Im completely out of ideas, what have i missed in configurations. It seems like client simply can't connect to daphne server, and i cant understand why. here is my docker-compose file: version: '3.9' services: db: container_name: postgres image: postgres:14.6 volumes: - ./init.sql:/docker-entrypoint-initdb.d/init.sql - ./postgres_data:/var/lib/postgresql/data/ - .:/app environment: - POSTGRES_DB=${DB_NAME} - POSTGRES_USER=${POSTGRES_USER} - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} - "POSTGRES_HOST_AUTH_METHOD=trust" restart: "on-failure" networks: - assemble nginx: build: ./nginx networks: - assemble volumes: - ./nginx/cert:/nginx/cert ports: - "80:80" - "443:433" depends_on: - db - daphne redis: image: redis networks: - assemble ports: - 6379:6379 depends_on: - db daphne: build: context: ./WebService dockerfile: Dockerfile image: latest volumes: - ./static:/engine_side/static - .:/app networks: - assemble depends_on: - db - gunicorn - redis ports: - 9000:9000 expose: - 9000 gunicorn: build: context: ./WebService dockerfile: Dockerfile volumes: - .:/app - ./static:/engine_side/static environment: - DJANGO_SUPERUSER_USERNAME=${DJANGO_SU_USERNAME} - DJANGO_SUPERUSER_PASSWORD=${DJANGO_SU_PASSWORD} - DJANGO_SUPERUSER_EMAIL=${DJANGO_SU_EMAIL} - POSTGRES_NAME=${DB_NAME} - POSTGRES_USER=${POSTGRES_USER} - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} … -
Time and date calculations DJango
So i have a data entry project using django and i have those 4 fields representing the: start_date, start_time, end_date, and end_time {% block content %} <h1>Form Page</h1> {% csrf_token %} {{ form.start_date.label_tag }} {{ form.start_date }} {{ form.start_time.label_tag }} {{ form.start_time }} {{ form.end_date.label_tag }} {{ form.end_date }} {{ form.end_time.label_tag }} {{ form.end_time }} {{ form.duration_hours.label_tag }} {{ form.duration_hours }} Submit {% endblock %} so the thing that i need is to make a listener for those 4 field values and whenever the user entered the first 3 values and start filling up the forth one which will be the end time the duration_hours field will start to calculate the difference between and give me the value of the duration time. All models,forms python files are correct i just want to know how i can do it I tried to make a script in the html file like this : <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"\>\</script\> $(document).ready(function(){ // get the values of the start and end date/time fields var start_date = $("#start_date input").val(); var start_time = $("#start_time input").val(); var end_date = $("#end_date input").val(); var end_time = $("#end_time input").val(); // combine the start date/time and end date/time into Date objects var start_datetime = new … -
Count objects in queryset by value in a field
I have a queryset that is returned by the server: queryset = Item.objects.all() ItemSerializer(queryset, many=True).data [OrderedDict([('id', '123'), ('status', 'Available')]), ... OrderedDict([('id', '321'), ('status', 'Confirmed')])] I can get the number of items by status: queryset.values('status').annotate(Count('status')) <QuerySet [{'status': 'Available', 'status__count': 3}, {'status': 'Confirmed', 'status__count': 2}]> As a result, I am trying to get such a response from the server: [{"id":"123","status":"Available"}, ... {"id":"321","status":"Confirmed"}, {"status": "Available", "status__count": 3}, {"status": "Confirmed", "status__count": 2}] -
Tools to help in analyzing and reviewing large python code base
I have a large Django code base which I want to analyze and review.Is there any tools that can help me to do this efficiently like explain the code architecture,flow and give me high level overview? -
Django Smart Selects not working for django admin
So I'm trying to implement django-smart-selects 1.5.9 for django 1.11.4 and somehow the chained keys dont work the way they should. models.py class Province(models.Model): name = models.CharField( max_length=30 ) class Meta: verbose_name = _("province") verbose_name_plural = _("provinces") def __str__(self): return self.name class District(models.Model): province = models.ForeignKey( Province, on_delete=models.CASCADE ) name = models.CharField( max_length=50 ) class Meta: verbose_name = _("district") verbose_name_plural = _("districts") def __str__(self): return self.name class City(models.Model): district = models.ForeignKey( District, on_delete=models.CASCADE ) name = models.CharField( max_length=50 ) class Meta: verbose_name = _("city") verbose_name_plural = _("cities") def __str__(self): return self.name class Ward(models.Model): city = models.ForeignKey( City, on_delete=models.CASCADE ) name = models.CharField( max_length=2 ) class Meta: verbose_name = _("ward") verbose_name_plural = _("wards") def __str__(self): return self.name class School(models.Model): # other fields ..... province = models.ForeignKey( Province, on_delete=models.SET_NULL, blank=True, null = True, verbose_name = _("province") ) district = ChainedForeignKey( District, chained_field="province", chained_model_field="province", show_all=False, ) city = ChainedForeignKey( City, chained_field="district", chained_model_field="district", show_all=False, ) ward = ChainedForeignKey( Ward, chained_field="city", chained_model_field="city", show_all=False, ) urls.py url(r'^admin/', admin.site.urls), url(r'^admin/', include('smart_selects.urls')), admin.py @admin.register(School) class SchoolAdmin(admin.ModelAdmin): inlines = [ServerInline, ServerUpdateInline] list_display = ['school_name', 'school_type','phone', 'province', 'district', 'city', 'ward', ] search_fields = ('school_name','district__name') list_filter = ('school_type', 'district') here tried the chained dropdown implementation from django-smart-selects the models and admin … -
Relate model to itself in django for recommendations
Im trying to relate django model to itself. I have Product table and recommendations column. I wanna relate recommendations to itself. How can I do it? class Product(models.Model): @property def image_url(self): if self.img and hasattr(self.img, 'url'): return self.img.url name_tm = models.CharField(max_length=255) name_ru = models.CharField(max_length=255) name_en = models.CharField(max_length=255) child_category = models.ForeignKey(Child_Category, on_delete=models.CASCADE, related_name='child_category') show = models.BooleanField(default=True) description_tm = models.TextField(blank=True, null=True) description_ru = models.TextField(blank=True, null=True) description_en = models.TextField(blank=True, null=True) price = models.DecimalField(decimal_places=2, max_digits=8) ready_time = models.PositiveIntegerField(null=True, blank=True) created_time = models.DateTimeField(auto_now_add=True) updated_time = models.DateTimeField(auto_now=True) recommendations = models.ManyToManyField(Product, blank=True, null=True) img = models.FileField(upload_to=upload_to, null=True) def __str__(self): return self.name_en -
Fail to load resource: the server responded with a status of 404. in the STATICFILES_DIRS setting does not exist
I'm trying to put image on my website with Django. But it always give an error 404, Tried many things, but it still be the problem. MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATICFILES_DIRS = [ os.path.join(PROJECT_ROOT, 'static'), ] STATIC_URL = '/static/' {% load static %} <!DOCTYPE html> <html> <img src="{% static 'media/logo2.jpeg' %}" alt="photo" height="100" width="500"> <p>HEllo world</p> {% block content %} replace me {% endblock %} </html> Wanna to have image on the website! -
Celery crashing error: redis.exceptions.ResponseError: UNBLOCKED force unblock from blocking operation, instance state changed (master -> replica?)
I am using celery in my django project to run some tasks in async. But the celery on server is crashing repeatedly. Error message: Mar 20 10:47:51 QA celery[663]: chan.handlers[type]() Mar 20 10:47:51 QA celery[663]: File "/var/www/gateway/env/lib/python3.10/site-packages/kombu/transport/redis.py", line 896, in _brpop_read Mar 20 10:47:51 QA celery[663]: dest__item = self.client.parse_response(self.client.connection, Mar 20 10:47:51 QA celery[663]: File "/var/www/gateway/env/lib/python3.10/site-packages/redis/client.py", line 1192, in parse_response Mar 20 10:47:51 QA celery[663]: response = connection.read_response() Mar 20 10:47:51 QA celery[663]: File "/var/www/gateway/env/lib/python3.10/site-packages/redis/connection.py", line 829, in read_response Mar 20 10:47:51 QA celery[663]: raise response Mar 20 10:47:51 QA celery[663]: redis.exceptions.ResponseError: UNBLOCKED force unblock from blocking operation, instance state changed (master -> replica?) Mar 20 10:47:51 QA systemd[1]: celery.service: Deactivated successfully. Mar 20 10:47:51 QA systemd[1]: celery.service: Consumed 2.439s CPU time. Can anyone help? Is there any was to prevent this error. -
Pytest-django does not seem to create a new database for each test
When I run a test that needs the database, it seems to use the existing database (when I change a database entry, the test error contains the changed database entry). But I expect that pytest-django creates a new database for each test (if not specified differently). When debugging it calls the custom django_db_setup and the pytest django_db_setup fixture. It also outputs in the log statement: "Running migrations: Applying ..." but the test fails when I manipulate the data in the existing database. Could it be that the problem is there because we use an in memory Sqlite database? Or do I need some other setting? Or is this a bug? Test: def test_should_show_the_city_name_in_city_select_dropdown(page: Page, django_db_setup): page.goto("/") city_select_button = page.get_by_text("Stadt auswählen") city_select_button.click() assert "Beispielstadt" in page.get_by_role("listitem").all_inner_texts() conftest.py import os import pytest from django.core.management import call_command from config.settings.base import BASE_DIR os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true" @pytest.fixture(scope="session") def django_db_setup(django_db_setup, django_db_blocker): with django_db_blocker.unblock(): call_command( "loaddata", os.path.join(BASE_DIR, "e2e_tests", "database", "test_database.json"), ) pyproject.toml [tool.poetry.dependencies] python = "^3.10" django = "^4.1.6" [tool.poetry.group.dev.dependencies] pytest = "^7.2.1" pytest-playwright = "^0.3.0" pytest-base-url = "^2.0.0" pytest-django = "^4.5.2" [tool.pytest.ini_options] base_url = "http://localhost" DJANGO_SETTINGS_MODULE = "config.settings.local-container" database settings DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": Path("/") / "db" / "db.sqlite3", } } -
Django UpdateView not working showing slug error
I'm having issues with my creating an update view to update aspects of a model. Below is the code urls from django.urls import path, include from . import views urlpatterns = [ path('', views.Tenant_selector.as_view(), name='Tenant_selector'), path('<slug:slug>/dashboard', views.Dashboard.as_view(), name='Dashboard'), path('<slug:slug>/updateTenant', views.EditTenant_View.as_view(), name='UpdateTenant'), path('createTenant', views.CreateTenant_View.as_view(), name='CreateTenant'), path('<slug:slug>/sync', views.sync_view.as_view(), name='Sync'), path('success', views.Success.as_view()), path('<slug:slug>/loading', views.sync_loading.as_view(), name='Loading'), path('createTenant', views.CreateTenant_View.as_view(), name='CreateTenant'), ] views from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.views.generic.edit import CreateView, UpdateView from django.views.generic import TemplateView, DetailView, ListView from account.forms import CreateTenant, EditTenant from account.models import Tenant, staff_sync_model, student_sync_model from main.forms import RegisterForm, EditUser from main.models import NewUser from django.http import HttpResponse from datetime import date from . import Sync class Dashboard(TemplateView): template_name = "dashboard.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) self.data = Tenant.objects.get(slug=self.request.path.split("/")[2]) context['total'] = self.data.staff.count() + self.data.student.count() context['staff'] = self.data.staff.count() context['student'] = self.data.student.count() context['slug'] = self.request.path.split("/")[2] return context class CreateTenant_View(CreateView): model = Tenant form_class = CreateTenant template_name='CreateTenant.html' success_url='/account/success' def form_valid(self, form): obj = form.save(commit=False) obj.user = self.request.user obj.save() return redirect('/account/success') class EditTenant_View(UpdateView): model = Tenant form_class = EditTenant template_name='UpdateTenant.html' success_url='/account/success' def form_valid(self, form): form.save return redirect('/account/success') class Success(TemplateView): template_name='success.html' class Tenant_selector(ListView): model = Tenant template_name = 'Tenant_selector.html' def get(self, request, *args, **kwargs): if self.request.user.is_authenticated: data = self.request.user.tenant_set.all() if len(data) … -
Cannot parse data into {% include %} tag - Django
i have forum.html template inside templates/forum directory <div style="height:50px; width:100%">welcome to forum {{ obj.forum_name }}</div> i want to include this template into my topic.html template which is inside same directory. and i want to pass data using with {% include 'forum/forum.html' with obj.forum_name="windmaker" %} However it does not work as expected. It gives me "with" in 'include' tag needs at least one keyword argument. error. What can i do? As far as i understood the problem arise from dot(.) operator. I tried not to using it and suddenly it renders the page correctly here i get rid of .forum_name inside forum.html <div style="height:50px; width:100%">welco to forum {{ obj }}</div> and here i passed data inside topic.html {% include 'forum/forum.html' with obj="windmaker" %} and suddenly it works! -
from django.contrib.auth.models import User error in class Meta:
I'm having a problem to create a User inside class Meta I saw some things related to the same problem but could not solve with the solutions they gave. Here the problem: enter image description here I had this same problem in models.py but looking a little on the internet I could find how to fix and had to import the settings and create the user with this AUTH_USER_MODEL enter image description here I tried to do the same thing on the form but I got these two errors. enter image description here enter image description here And when trying to put only the settings.AUTH_USER_MODEL I can not put the server to run because it gives me this error in the Meta class and when I replace for example an empty string it runs normally but then I will not be creating the user. enter image description here enter image description here -
How do i limit choices for a field in a django model with respect to the data in previous field using foreignkey and limit_choices_to attribute?
class Property(models.Model): property_name = models.CharField(max_length=100) unit_name = models.CharField(max_length=100) class Tenant(models.Model): tenant_name = models.CharField(max_length=100) rent_unit = models.ForeignKey(Property, on_delete=models.SET_NULL) class Payment(models.Model): payment_name = models.ForeignKey(Tenant, on_delete=models.SET_NULL) payment_property = models.ForeignKey(Property, on_delete=models.SET_NULL, limit_choices_to={ 'pk__in': Property.objects.filter(unit_name=models.OuterRef('payment_name__rent_unit__unit_name')) }) I'am trying to limit the choices for the payment_property field in the Payment model based on the selected rent_unit in the Tenant model using Django's ForeignKey.limit_choices_to attribute with a subquery. But am getting this error when trying to execute makemigrations. ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. i was expecting to get a single choice for payment_property whenever i create a new Payment object and select a Tenant object, the available choices for the payment_property field should be limited to Property objects that have the same unit_name as the rent_unit of the selected Tenant object.