Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
UnicodeDecodeError after adding "ó" character in template
i wanted to test new django project in Visual Studio 2019. But when i add "ó" or "ą" character in template i get error "'utf-8' codec can't decode byte 0xf3 in position 280: invalid continuation byte" My own project working well on VS Code. But this one premade by VS 2019 not. {% extends "app/layout.html" %} {% block content %} {{ title }}. {{ message }} One Microsoft Way Redmond, WA 98052-6399 P: 425.555.0100 Support: ó Support@example.com Marketing: Marketing@example.com {% endblock %} -
DRF transmit errors through functions
I know that this question may be already asked or be very obvious but I cannot find anything about it. Let's say we have this method in views.py: def my_api_view(request): if request.method == "POST": return HttpResponse(other_function()) else: return HttpResponse("{UERR:%s}" % {UERR_POST_REQUEST_EXPECTED}) where other_function() is a function in another file in another directory outside of Django app: def other_function(): a = function1() b = function2() return function3(a,b) Question: From other_function(), function1(), function2() or function3(a,b) how do we make our view to return an HttpResponse with an error? -
Login form django using ajax
I have a login form of Django and i want to redirect user to the landing page if the password and the username is matching and to show an alert message if the login is failed and eventually show a validation error if the form is submitted empty. When i submit the form using the right credentials the user is logged but no message is shown on the form, on the server log i have this message 09/May/2019 23:35:52] "POST /login/ HTTP/1.1" 200 7560 when i submit an empty form i have this message Bad Request: /login/ [09/May/2019 23:36:53] "POST /login/ HTTP/1.1" 400 0 and when i submit a wrong credentials i have this message [09/May/2019 23:37:36] "POST /login/ HTTP/1.1" 200 61 This is my html form <div id="cd-login"> <!-- log in form --> <div class="login_div"></div> <form id="login_form" class="cd-form" action="{% url 'login' %}" method="POST"> {% csrf_token %} <p class="fieldset"> <label class="image-replace cd-email" for="signin-email">E-mail</label> <input class="full-width has-padding has-border" id="username" type="text" name="username" placeholder="E-mail"> <span class="cd-error-message">Error message here!</span> </p> <p class="fieldset"> <label class="image-replace cd-password" for="signin-password">Password</label> <input class="full-width has-padding has-border" id="password" type="text" name="password" placeholder="Password"> <a href="#0" class="hide-password">Hide</a> <span class="cd-error-message">Error message here!</span> </p> <p class="fieldset"> <input class="full-width" type="submit" value="Login"> </p> </form> <p class="cd-form-bottom-message"><a href="#0">Forgot your … -
django.contrib.postgres missing/not installing on Heroku Django
I'm using the unaccent extension for Postgres and followed all the docs to get it to work (installed the extension on the database directly via CREATE EXTENSION and put django.contrib.postgres in INSTALLED_APPS in django settings). In local environment it's working perfectly, however after building and deploying the app to Heroku it looks like Heroku isn't installing django.contrib.postgres. Therefore, when i try to use the functionality of my app that queries using unaccent i get the Unsupported lookup 'unaccent' for CharField that happens when you don't have django.contrib.postgres in INSTALLED_APPS. In python shell printing settings.INSTALLED_APPS on local environment shows that django.contrib.postgres is there but running it on Heroku shows it's missing. Is it unsupported on the buildpack for heroku/python or am i missing something? I tried to pip install the django-contrib-postgres backport for earlier versions of Django to no avail. Python version is 3.6.7 and Django is 2.1.2. Creating the extension via migrations using UnaccentExtension doesn't change anything too and i'm sure it's not Postgres problem because querying directly on the database using unaccent(columnname) works as expected. Thanks in advance. -
PlayerForm.is_valid always false but player is still saving
I designed a leaderboard app where there are players and games. When you register, it creates a Django user and creates a Player object that is associated with the user. When I register, if PlayerForm.is_valid is true, the user and player is created where PlayerForm(UserCreationForm) and it renders a the elosearch.html, otherwise, it returns to the register.html. I can see that the player and user is being created but when I submit the request it is rendering register.html rather than elosearch.html. How is it rendering the wrong view if is_valid produces true and if it doesn't, why are the player and user saving? I created my own html form so I don't actually need to pass the form to the template (args is not used) PlayerForm class PlayerForm(UserCreationForm): username = forms.CharField(required=True) email = forms.EmailField(required=True) class Meta: model = User fields = ( 'username', 'email', 'password1', 'password2', ) def save(self, commit=True): user = super(PlayerForm, self).save(commit=False) user.username = self.cleaned_data['username'] user.email = self.cleaned_data['email'] user.password1 = self.cleaned_data['password1'] user.password2 = self.cleaned_data['password2'] new_player = Player(name=str(user.username), user=user) if commit: user.save() new_player.save() return user Register View def register(request): if request.method == 'POST': form = PlayerForm(request.POST) if form.is_valid(): form.save() return render(request, 'elousers/elosearch.html') else: return render(request, 'elousers/register.html') else: form = … -
UpdateView doesn't upload new image - Django
I have this updateview, all fields work except to tripLogo. class TripUpdate(LoginRequiredMixin, UpdateView): model = Trip template_name = 'tripplanner/basic_trip_arguments.html' fields = ['tripName', 'tripLogo', 'start_date', 'end_date'] success_url = '/' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): detailView = self.get_object() if self.request.user in detailView.owners.all(): return True return False In function way I know you need to use request.FILES, but I don't know how to do this in classes. Kind regards -
I am having trouble with understand a line of code
I am having trouble understand this line of code @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() why is profile lowercase in "instance.profile.save()" The code works, i read through the django docs trying to find the answer but i cant. This actually madee my project work completely, but i dont use things i dont understand. my model looks like this. class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) image = models.FileField(default='No_picture_available.png') School = models.CharField(max_length=200,null=True) Profession = models.CharField(max_length=90, null=True) Bio = models.TextField(max_length=500,null=True) FullName = models.CharField(max_length=80, null=True) age = models.IntegerField(null=True) def __str__(self): return f'{self.user.username} Profile please explain why profile is lowercase in the profile save signal function instead of capitalize. if i put it capitalize i get an error. -
Display Table and Form in Django View
I am attempting to return a form and table in the same view so that they appear in the same screen. I know that the below code does not work, it is to illustrate what I want to do - I have my CreateManifestForm and manifests = Manifests.objects.all() should populate the table which is present in the template. The problem is when I render this - it shows the form, and just the blank table. I have populated the table using a separate view so I know that it is set up properly on its own, but how can I render {'form': form} and context at the same time? Views.py: def add_manifest(request): manifests = Manifests.objects.all() context = { 'manifests' : manifests, } if request.method == "POST": form = CreateManifestForm(request.POST) if form.is_valid(): form.save() return redirect('display_orders') else: form = CreateManifestForm() return render(request, 'add_manifest.html', {'form': form}) return render(request, 'add_manifest.html', context) -
How to add drag-and-drop elements to frontend?
I'm in the process of creating a Django webapp and one of the apps requires the order of elements on the page to be rearranged by the owner of the content dynamically. I've been looking into this and haven't really found a solution that would work with Django. So far, I think using a table might be the best way of doing this, but I'm not sure about how to implement it. I was looking at http://tabulator.info/ which has a drag and drop sortable table that might work, but again, not sure how to go about integrating it with Django. I know it's easy to implement drag and drop elements into HTML, but what I need is for the moved elements to SAVE so that when the user comes back to the page, they're in the order they were left at. Any help or links would really be appreciated! -
Is there a way to combine Django Admin List filters such that selected filters all run at the same time?
Django 1.x, Django Admin list view, with a number of various kinds of filters (list filters). Users need to pick 3,4,5 options, sometimes involving typing, and they find it cumbersome to deal with the page reloading after each option is selected. Is there a way to setup filters so that they will not be applied until the user clicks a button? Is hand crafting your own HTML fields in a template the only way to go here? I'm looking at using JQuery to check when filters are changed, but Django forces an update after every filter option is selected. All the Django admin related events seem promising, but they have not been helpful so far - for example you can get each queryset that filters create, but by then the battle's already been lost. Ideally a user could open the Django Admin list view, set several filters, then press a button to cause them all to be applied to the data. -
Conditionals in django models arguments
quick question. Does anyone have any idea how to write conditionals in django models? For example I have this code here: class Trip(models.Model): tripName = models.CharField(max_length=64) tripLogo = models.ImageField(default='default_trip.jpg', upload_to='trip_pics') So here default value is 'default_trip.jpg', but I'd like to write a conditional that if tripName == "russian" than default=russia.jpg. Maybe not change default, but another image will be initiated. -
Is there a better way to check for a foreign key relationship existence in a django form?
I have a current check in the post function of my form that checks to see if the selected van is already in use. I want to know if there is a better way of doing this? The field I am checking other objects for is "van_used" and the attribute that van_used stores from the related model (it is a foreign key) is "vanName" here is the post function from my class: def post(self, request): """Take in user data, clean it, and then post it to the database.""" form = self.form_class(request.POST) # pass in the user's that was submitted in form if form.is_valid(): trip = form.save(commit=False) # create an object so we can clean the data before saving it first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] trip_start = form.cleaned_data['trip_start'] trip_end = form.cleaned_data['trip_end'] van_used = form.cleaned_data['van_used'] if trips.objects.filter(van_used = form.cleaned_data['van_used']).exists(): messages.warning(request, van_used.vanName + ' is currently in use. Pick another vehicle.' ) return render(request, self.template_name, {'form': form}) Please let me know any suggestions for improvement, currently the check I have in place only runs when the user clicks submit. It'll reject the form and have them start over. I'd like to have a bit more forewarning to the user if possible. Thanks … -
DRF - how to reverse a class based view in api_root
In Django REST Framework, I'm trying to add an API root to a views.py that has class based views. Error: $ http http://127.0.0.1:8000/api/ Error - django.urls.exceptions.NoReverseMatch: Reverse for 'SnippetListView' not found. 'SnippetList' is not a valid view function or pattern name. backend/views.py from backend.models import * from backend.serializers import * from rest_framework import generics from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.reverse import reverse @api_view(['GET']) def api_root(request, format=None): return Response({ 'snippets': reverse('SnippetList') # 'snippets': reverse('SnippetListView') # 'snippets': reverse('snippet-list') # 'snippets': reverse('snippet_list') }) class SnippetList(generics.ListCreateAPIView): queryset = Snippet.objects.all() serializer_class = SnippetSerializer class SnippetDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Snippet.objects.all() serializer_class = SnippetSerializer backend/urls.py from backend import views from django.urls import path, include from rest_framework.urlpatterns import format_suffix_patterns urlpatterns = [ path('', views.api_root), path('snippets/', views.SnippetList.as_view()), path('snippets/<int:pk>/', views.SnippetDetail.as_view()), ] Docs: https://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis/#creating-an-endpoint-for-the-highlighted-snippets -
Redirect after download file with return response
I got a function to create a plain text in mi views.py: def txt_file(data, headers): filename = datetime.datetime.now() content = '' for value in data: for key in headers: content += str(value[key]) + ";" content += ";;;;;;;;;;;;;\n" response = HttpResponse(content, content_type='text/plain') response['Content-Disposition'] = 'attachment; filename={0}'.format(filename) return response This function is called from a button in the template, the file downloads ok, but I need that inmediatly after the download is complete, it redirect to a url. ***I already tried javascript document.location (but it executes the request too fast so the template reloads and the file gets lost, also tried a timeout but the download time it's relative so its not a solution. It's there a way to do it? -
How to set up a tablespace to run pytest django in an oracle schema?
I was working on django using SQLite3 as backend. Then we have to migrate all of it to an oracle DB. I'm having a lot of problems trying to run pytest on the schemas. How can I do that? Here is what I have tried so far: added in settings each schema: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': service_name, 'USER': username, 'PASSWORD': password, 'HOST': hostname, 'PORT': port, 'TEST': { 'TBLSPACE': 'name_tablespace' }, 'schema2': { 'ENGINE': 'django.db.backends.oracle', 'NAME': service_name, 'USER': username, 'PASSWORD': password, 'HOST': hostname, 'PORT': port, 'TEST': { 'TBLSPACE': 'name_tablespace' }, 'schema3': { 'ENGINE': 'django.db.backends.oracle', 'NAME': service_name, 'USER': username, 'PASSWORD': password, 'HOST': hostname, 'PORT': port, 'TEST': { 'TBLSPACE': 'name_tablespace' } }, then I defined a fixture on the test file to use the schema as test db: @pytest.fixture(scope='session') def django_db_setup(): settings.DATABASES['default'] = { 'ENGINE': 'django.db.backends.oracle', 'NAME': service_name, 'USER': username, 'PASSWORD': password, 'HOST': hostname, 'PORT': port, 'DEFAULT_TABLESPACE': 'tablespace_name' }, When I run pytest, the tests pass but at the end it flush the DB. How can I point the tablespace for test instead of the schema_db. I don't want to lose whatever data is in the DB from users. I'm new with this, Let me know if this is … -
Rewriting function into class
I have a function for changing password of a user, now I'd like to rewrite it to a class view, it gives me an error: __init__() missing 1 required positional argument: 'user' Function: def change_password(request): if request.method == 'POST': form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) messages.success(request, 'Your password was successfully updated!') return redirect('profile') else: messages.error(request, 'Please correct the error below.') else: form = PasswordChangeForm(request.user) return render(request, 'accounts/change_password.html', { 'form': form }) Class View so far class ChangePasswordView(FormValidMessageMixin, FormInvalidMessageMixin, FormView): form_class = PasswordChangeForm template_name = 'accounts/change_password.html' success_url = reverse_lazy('profile') def get_form_valid_message(self): return 'Your password was successfully updated!' def get_form_invalid_message(self): return 'Please correct the error below.' def form_valid(self, form): form.instance.author = self.request.user form.save() return super().form_valid(form) -
Django-SES BotoServerError: 403 Forbidden
I am trying to send email from django with django-ses library but getting error: boto.exception.BotoServerError: BotoServerError: 403 Forbidden <ErrorResponse xmlns="http://ses.amazonaws.com/doc/2010-12-01/"> <Error> <Type>Sender</Type> <Code>SignatureDoesNotMatch</Code> <Message>The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.</Message> </Error> <RequestId>7e2103e0-729f-11a9-aq25-51a2dqa8ae97</RequestId> </ErrorResponse> I verified the domain and verified admin address admin@...com address in AWS console and created API key and secret from the SES dashboard. Django settings: EMAIL_BACKEND = 'django_ses.SESBackend' AWS_SES_ACCESS_KEY_ID = os.environ.get('AWS_SES_ACCESS_KEY_ID') AWS_SES_SECRET_ACCESS_KEY = os.environ.get('AWS_SES_SECRET_ACCESS_KEY') AWS_SES_REGION_NAME = 'eu-west-1' # because I use ireland server, but same error without this SERVER_EMAIL = 'admin@...com' DEFAULT_FROM_EMAIL = '"Hello You" <no-reply@...com>' and I try to send email with: from django.core.mail import EmailMessage from django.conf import settings email = EmailMessage( 'Hello', 'World', settings.DEFAULT_FROM_EMAIL, to=['mail@example.com'] ) email.send() What can be a problem here? -
Indentation error - Django, on trying to resolve unexpected keyword argument 'force_insert' error
I have the following code, and on looking up possible solutions tried to resolve the problem by using the replacement code, but have a persistent indentation error and I cannot seem to see why, as the indentation is correct. Original code (which works with no errors on running server) but causes the force_insert error. models.py from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) Replaced with: from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300,300) img.thumbnail(output_size) img.save(self.image.path)' On running the second bit of code in models.py, i get the following error in the server File "C:\Users\User\Desktop\DjangoFacebook\pseudofacebook\users\models.py", line 24 def save(self, *args, **kwargs): ^ IndentationError: unexpected indent I tried running makemigrations and migrate, in case something was wrong on the execution front, but the … -
Return object id after file is uploaded
I have a simple Django app to upload an image file using a form. I'd like to be able to use the id (primary key assigned in the model) in the view function. How can I get that primary key? I feel like I must be missing something simple. Model: class image(models.Model): image = models.ImageField(upload_to='images/') uploaded_at = models.DateTimeField(auto_now_add=True) views.py: def image_upload(request): if request.method == 'POST': form = ImageForm(request.POST, request.FILES) if form.is_valid(): form.save() # id = ?????????? # Some other processing with id... return render(request, 'image_uploaded.html', context=context) else: form = ImageForm() return render(request, 'reader/image_form.html', { 'form': form }) forms.py class ImageForm(forms.ModelForm): class Meta: model = image fields = ('image', ) -
Django root logger, empty string or 'root'
I have seen many posts about configuring django root loggers, but varying with 'root' and '' empty string: 'loggers': { 'root': { 'level': 'DEBUG', 'handlers': ['general', 'console'], 'formatter': 'details', } ... } OR 'loggers': { '': { 'level': 'DEBUG', 'handlers': ['general', 'console'], 'formatter': 'details', } ... } And I have not yet seen a official/authoritative documentation/answer telling me which one is the CORRECT way to specify root logger. Could someone please put a definitive answer to this? -
Django annotate to joined model
I have a Alarm model and I have a HistoryAlarm model. An Alarm model. An HistoryAlarm model with foreign key to Alarm model. class Alarm(models.Model): name = models.CharField(max_length=256, unique=True) value = models.BooleanField() my_json_field = JSONField(null=True, blank=True, default={}) created_at = models.DateTimeField(editable=False) class HistoryAlarm(models.Model): alarm = models.ForeignKey(Alarm, on_delete=models.CASCADE) value = models.BooleanField() created_at = models.DateTimeField(editable=False) I wrote the HistoryAlarmSerializer reusing the AlarmSerializer: class AlarmSerializer(serializers.ModelSerializer): annotated_field = serializers.SerializerMethodField() def get_annotated_field(self, obj): return obj.annotated_field class Meta: model = Alarm fields = '__all__' class HistoryAlarmSerializer(serializers.ModelSerializer): alarm = AlarmSerializer(read_only=True) ... class Meta: model = HistoryAlarm fields = '__all__' The annotated_field in the AlarmSerializer is created like this: Alarm.objects.all().annotate( annotated_field=KeyTextTransform('my_key', 'my_json_field') ) When I try to get my serialized list of alarms I get what I want. Problem: I get an error from the AlarmSerializer method get_annotated_field when I try to get a list of my history alarms: 'Alarm' object has no attribute 'annotated_field' So now I'm trying to annotate the special field but I cannot find a way to do it. Below I would get a list of elements that responds to history_alarm.annotated_field and not to history_alarm.alarm.annotated_field. HistoryAlarm.objects.all().annotate( annotated_field=KeyTextTransform('my_key', 'my_json_field') ) How could I possibly achieve this? -
Django REST; use queryset on a manytomany field to filter that related field
I am using the Django REST framework and cannot figure out how to filter the results of a subfield (manytomany field) that return when the referencing model/view is queried. I have a Tag model that is related to a Book model via a manytomany field. When querying for tags it returns all the book associated with it. However, I need to filter the books to only include Books that the current user has access to. I can get this filtered properly in the Book view, but I cannot figure out how to get this working for the tag view // Book model: class BookQuerySet(models.QuerySet): def visible_to(self, user): if user.can_see_secrets: return self return self.exclude(secret_book=True) class Book(models.Model): id = models.AutoField(db_column='Id', primary_key=True) name = models.CharField(db_column='CatalogNumber', unique=True, max_length=50) secret_book = models.IntegerField(db_column='secret', default=False) objects = BookQuerySet.as_manager() class Meta: managed = False db_table = 'book' app_label = 'core' // Book view: class BooksFilteringBackend(filters.BaseFilterBackend): def filter_queryset(self, request, queryset, view): current_user = request.user queryset = queryset.visible_to(current_user) return queryset class BookViewSet(viewsets.ReadOnlyModelViewSet): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) queryset = Book.objects.all() filter_backends = (BooksFilteringBackend,) serializer_class = BookSerializer There is a BookSerializer that doesnt do anything interesting Now the above works, if a user queries the book view they only get … -
Navigating many2many relationships in both directions
I'm trying to understand how Django returns columns from foreign keys, particularly the m2m situation, easy in SQL but I'm trying to get into Django. In this example I have 3 models, Sample which has a m2m with Container and Location which has a 1-to-many with Container. Scenario 1a: From the Sample table get the Containers that sample is in(return sample_number and container_name). Scenario 1b: From the Container get the related Samples (return container_number and sample_number). Scenario 2a: From the Location model get the containers (location_name and container_names). Scenario 2b: From the Container model get the location (Container_name and location_name). Hopefully this will serve as a good overall reference for others. # models.py class Location(models.Model): location_id = models.AutoField(primary_key=True) location_name = models.CharField(max_length=100, blank=True, null=True) class Sample(models.Model): sample_id = models.AutoField(primary_key=True) sample_number = models.IntegerField() class Container(models.Model): #like a friend container_id = models.AutoField(primary_key=True) container_name = models.CharField(max_length=50, blank=True, null=True) location_id = models.ForeignKey(Location, db_column='location_id', on_delete = models.PROTECT, related_name = 'location') samples = models.ManyToManyField('Sample', through='ContainerSamples', related_name='containers') # views.py - Implements a filter def detailcontainer(request, container_id): container = get_object_or_404(Container, pk=container_id) samples = container.samples.all() container_contents = container.samples.all() unassigned_samples = Sample.objects.all() qs = Sample.objects.all() context = { 'queryset': qs, 'container':container, 'container_contents': container_contents, 'unassigned_samples': unassigned_samples, } return render(request, 'container/detailcontainer.html', context) # … -
Wagtail (Django CMS) how to add single image in wagtail, simple attempt ends with "OperationalError no such column: gallery_gallerysubpage.cover_id"
My problem is trivial, I just don't know how to add single image as Page miniature. Here's my page model (I tried like shown in ImageChooserPanel reference): class GallerySubpage(Page): intro = models.CharField(max_length=250) body = RichTextField(blank=True) # THIS IS TAKEN FROM DOCS cover = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) # This returns some dummy for a while. I want to replace this with some field that contain single Image def main_image(self): gallery_item = self.gallery_images.first() if gallery_item: return gallery_item.image else: return None search_fields = Page.search_fields + [ index.SearchField('intro'), index.SearchField('body'), ] content_panels = Page.content_panels + [ FieldPanel('intro'), FieldPanel('body', classname="full"), InlinePanel('gallery_images', label = "Images that will be displayed on this page"), # THIS IS TAKEN FROM DOCS ImageChooserPanel('cover'), ] When I run the code I get error: OperationalError at /gallery/galerry132/ no such column: gallery_gallerysubpage.cover_id -
Django. How to make search with dependent drop-down lists?
Tell me, please, if it is not difficult, how to write a script correctly, so that when choosing a region, only cities of this area are displayed, and when choosing a city, only areas of this city are displayed. Models: class Region(models.Model): name = models.CharField(max_length=100, verbose_name='Название области') def __str__(self): return self.name class City(models.Model): region = models.ForeignKey(Region, on_delete=models.CASCADE, verbose_name='Область') name = models.CharField(max_length=100, verbose_name='Название города') def __str__(self): return self.name class District(models.Model): city = models.ForeignKey(City, on_delete=models.CASCADE, verbose_name='Город') name = models.CharField(max_length=100, verbose_name='Название района') def __str__(self): return self.name views.py def search(request): districts = District.objects.all() cities = City.objects.all() regions = Region.objects.all() queryset_list = Listing.objects.order_by('-list_date') if 'region' in request.GET: region_id = request.GET.get('region') cities = City.objects.filter(region_id=region_id).order_by('name') if region_id: queryset_list = queryset_list.filter(region_id=region_id) if 'city' in request.GET: city_id = request.GET.get('city') districts = District.objects.filter(city_id=city_id).order_by('name') if city_id: queryset_list = queryset_list.filter(city_id=city_id) if 'district' in request.GET: district_id = request.GET.get('district') if district_id: queryset_list = queryset_list.filter(district_id=district_id) context = { 'districts': districts, 'cities': cities, 'regions': regions, 'listings': queryset_list, 'values': request.GET } return render(request, 'listings/search.html', context) Template <form action="" id="search" data-search-url="{% url 'search' %}"> <div class="form-row"> <div class="col-md-3 mb-3"> <label class="sr-only">Область</label> <select name="region" class="form-control" id="id_region"> <option selected="true" disabled="disabled">Область</option> {% for region in regions %} <option value="{{ region.pk }}">{{ region.name }}</option> {% endfor %} </select> </div> <div class="col-md-3 mb-3"> …