Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django channels tests fails
I have followed the tutorial from readthedocs: https://channels.readthedocs.io/en/stable/tutorial/index.html for django channels. Everything worked fine until the last part of the tutorial, about testing. Here is the test file as well as the traceback. # chat/tests.py from channels.testing import ChannelsLiveServerTestCase from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support.wait import WebDriverWait class ChatTests(ChannelsLiveServerTestCase): serve_static = True # emulate StaticLiveServerTestCase @classmethod def setUpClass(cls): super().setUpClass() try: # NOTE: Requires "chromedriver" binary to be installed in $PATH cls.driver = webdriver.Chrome() except: super().tearDownClass() raise @classmethod def tearDownClass(cls): cls.driver.quit() super().tearDownClass() def test_when_chat_message_posted_then_seen_by_everyone_in_same_room(self): try: self._enter_chat_room('room_1') self._open_new_window() self._enter_chat_room('room_1') self._switch_to_window(0) self._post_message('hello') WebDriverWait(self.driver, 2).until(lambda _: 'hello' in self._chat_log_value, 'Message was not received by window 1 from window 1') self._switch_to_window(1) WebDriverWait(self.driver, 2).until(lambda _: 'hello' in self._chat_log_value, 'Message was not received by window 2 from window 1') finally: self._close_all_new_windows() def test_when_chat_message_posted_then_not_seen_by_anyone_in_different_room(self): try: self._enter_chat_room('room_1') self._open_new_window() self._enter_chat_room('room_2') self._switch_to_window(0) self._post_message('hello') WebDriverWait(self.driver, 2).until(lambda _: 'hello' in self._chat_log_value, 'Message was not received by window 1 from window 1') self._switch_to_window(1) self._post_message('world') WebDriverWait(self.driver, 2).until(lambda _: 'world' in self._chat_log_value, 'Message was not received by window 2 from window 2') self.assertTrue('hello' not in self._chat_log_value, 'Message was improperly received by window 2 from window 1') finally: self._close_all_new_windows() # === Utility === def _enter_chat_room(self, room_name): self.driver.get(self.live_server_url + '/chat/') ActionChains(self.driver).send_keys(room_name + '\n').perform() WebDriverWait(self.driver, … -
How do I make the view to show a multi-step form that has forms and formsets
I want to use a multi-step form combined with some formsets in Django but I realize I need more experience on the subject. I also see that there is hardly much documentation about it and what little I find they take many things for granted. Can you help me understand how to create a view that serves as a multi-step and that saves the values of the forms and formsets? previously I was already using JS for the wizard, the only thing missing is that I save the values in the database. thanks :D Views.py def create_Presupuestos(request): extra_forms = 1 ParteFormSet = formset_factory(PresupuestosParteForm, extra=extra_forms, max_num=20) ManoObraFormSet = formset_factory(PresupuestosManoObraForm, extra=extra_forms, max_num=20) PagosFormSet = formset_factory(PresupuestosPagosForm, extra=extra_forms, max_num=20) presupuestosclientesform=PresupuestosClientesForm(request.POST or None) presupuestosvehiculosform=PresupuestosVehiculosForm(request.POST or None) presupuestosparteform=PresupuestosParteForm(request.POST or None) presupuestosmanoobraform=PresupuestosManoObraForm(request.POST or None) presupuestospagosform=PresupuestosPagosForm(request.POST or None) presupuestosfotosform=PresupuestosFotosForm(request.POST or None) if request.method == 'POST': formset = ParteFormSet(request.POST, request.FILES) manoObra_formset = ManoObraFormSet(request.POST, request.FILES,prefix='manoobra') pagos_formset = PagosFormSet(request.POST, request.FILES, prefix='pagos') if formset.is_valid() and manoObra_formset.is_valid() and pagos_formset.is_valid(): presupuestosclientesform.save() return redirect('presupuestos:index') else: formset = ParteFormSet() manoObra_formset = ManoObraFormSet(prefix='manoobra') pagos_formset = PagosFormSet(prefix='pagos') presupuestosfotosform = PresupuestosFotosForm(request.POST or None) return render(request,'Presupuestos/new-customer.html',{ 'presupuestosclientesform':presupuestosclientesform, 'presupuestosvehiculosform':presupuestosvehiculosform, 'presupuestosparteform':presupuestosparteform, 'presupuestosmanoobraform':presupuestosmanoobraform, 'presupuestospagosform':presupuestospagosform, 'presupuestosfotosform':presupuestosfotosform, 'formset':formset, 'manoObra_formset':manoObra_formset, 'pagos_formset':pagos_formset }) -
django-celery-results are not expiring even though CELERY_RESULT_EXPIRES is set
I have an every minute task running on celery beat and I'm using rabbimq as broker and have postgresql as database. As my task is running every minute and I'm storing task result in database, my database size is increasing continuously day by day. I was looking into expiration of stored task result. As per celery documentation there is a CELERY_RESULT_EXPIRES config which uses celery beat to do a cleanup. Seems like it's not happening as expected. What am I missing or do wrong? Any pointers would be really great help. Following are my celery settings defined in my django settings.py CELERY_BROKER_URL = os.getenv('CELERY_BROKER_URL', 'amqp://localhost') CELERY_RESULT_BACKEND = 'django-db' CELERY_CACHE_BACKEND = 'django-cache' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_ENABLE_UTC = False CELERY_TIMEZONE = 'UTC' CELERY_CREATE_MISSING_QUEUES = False CELERY_DEFAULT_QUEUE = 'celery' CELERY_TASK_TRACK_STARTED = True CELERY_SEND_EVENTS = True CELERY_SEND_SENT_EVENT = True CELERY_WORKER_MAX_TASKS_PER_CHILD = 25 CELERY_TASK_REJECT_ON_WORKER_LOST = True CELERYD_TIME_LIMIT = 60 CELERYD_SOFT_TIME_LIMIT = 50 CELERY_ACKS_LATE = True CELERYD_PREFETCH_MULTIPLIER = 1 CELERY_RESULT_EXPIRES = 1 * 60 Following is my celery.py import django import logging from celery import Celery from celery.schedules import crontab from kombu import Exchange, Queue log = logging.getLogger(__name__) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'xxx.settings') django.setup() app = Celery('xxx') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() app.conf.task_queues = ( … -
Django converting isoformat string datetime to tuple and rising error
I'm trying to update two datetimefields for the Skill entity in my db. I'm sure I'm passing an isoformat datetime string. When creating instead of updating everything works fine but on the update I get: Exception Type: TypeError Exception Value: fromisoformat: argument must be str Here is the code raising the TypeError: # create or update skill created = ibm_date_to_iso(clean_data["skill"]["created"]) updated = ibm_date_to_iso(clean_data["skill"]["updated"]) try: skill = Skill.objects.get( skill_id=clean_data["skill"]["skill_id"], snapshot=clean_data["skill"]["snapshot"] ) # update fields if skills exists already skill.name = clean_data["skill"]["name"], skill.type = clean_data["skill"]["type"], skill.status = clean_data["skill"]["status"], skill.created = created, skill.updated = updated, skill.language = clean_data["skill"]["language"], skill.description = clean_data["skill"]["description"], skill.dialog_settings = clean_data["skill"]["dialog_settings"] skill.uploads.add(u) except Skill.DoesNotExist: skill = Skill( skill_id=clean_data["skill"]["skill_id"], name=clean_data["skill"]["name"], type=clean_data["skill"]["type"], status=clean_data["skill"]["status"], created=created, updated=updated, language=clean_data["skill"]["language"], snapshot=clean_data["skill"]["snapshot"], description=clean_data["skill"]["description"], dialog_settings=clean_data["skill"]["dialog_settings"] ) skill.save() skill.uploads.add(u) # new page for the skill entity page = Page( title="notes for Skill {} snap {}".format( skill.name, skill.snapshot), content="This page is empty..." ) page.save() skill.save() The exception is raised on the last line (skill.save()) only when the DoesNotExist exception is not raised. Here is the Skill model: class Skill(models.Model): skill_id = models.CharField(max_length=36) name = models.TextField() type = models.TextField() status = models.TextField() created = models.DateTimeField() updated = models.DateTimeField() language = models.TextField() snapshot = models.IntegerField() description = models.TextField() dialog_settings = models.TextField() page … -
In Django how to add user to many-to-many filed
I like to add permission to those users who I add to a many-to-many relation. I have a Projekt model where I like to add multiple users like this: class Projekt(models.Model): def __str__(self): return str(self.projekt) projekt = models.TextField(max_length=150) company_name = models.ForeignKey('Company', on_delete=models.CASCADE, default=1) jogosult_01 = models.ManyToManyField(User) date = models.DateField(auto_now_add=True, auto_now=False, blank=True) I add the users in the Django Admin page with holding down cmd then save and it shows everything is OK. If try to get the values like this: {% for u in jogosult %} {{ u.jogosult_01 }} {% endfor %} it say auth.user none. views.py @login_required def projects(request): jogosult = Projekt.objects.filter(jogosult_01_id=request.user).order_by('-date') context = { 'jogosult': jogosult, } return render(request, 'stressz/projects.html', context) -
Django 'NoneType' object has no attribute 'file'
I have my code implemented like this and when there is no file how can i raise exception models.py @api_view(('GET',)) def i_view(request): data = Model.objects.first() response = HttpResponse( data.file, content_type='application/vnd.openxmlformats ) return response -
How to check If any List values Exist in 2 or More Database Tables?
I have following type of Django Model. class ClientPackageMapping(models.Model): user_id=models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=False) client_package=models.ForeignKey(ClientPackage,on_delete=models.CASCADE,blank=True, null=True) joined_date = models.DateField(null=True,blank=True) expiry_date = models.DateField(null=True,blank=True) class Meta: abstract=True @property def is_expired(self): if self.expiry_date< date.today(): return True return False class ClientPackageBasicStocks(ClientPackageMapping): stocks = ArrayField(models.CharField(max_length=5),null=True,blank=True) class ClientPackageSilverStocks(ClientPackageMapping): stocks = ArrayField(models.CharField(max_length=5),null=True,blank=True) class ClientPackageGoldStocks(ClientPackageMapping): stocks = ArrayField(models.CharField(max_length=5),null=True,blank=True) class ClientPackagePlatinumStocks(ClientPackageMapping): stocks = ArrayField(models.CharField(max_length=5),null=True,blank=True) Basically The idea is if certain user has stock in basic table but if same stock exists in another table i.e silver or gold there must be validation error. Is there any way I can check the incoming list values with database? if ClientPackagePlatinumStocks.objects.filter(stocks=[*self._data['stocks']]).exists(): raise ValidationError({'duplicate_stocks': f'Duplicate stocks!'}) I tried doing this way but I am not able to build or restrict user from adding package to silver when they already have the same package in basic any help will be very helpful. -
django form doesn't display labels
I'm new in django. I try to create a simple form based on the model. Imputs are displayed fine but i have problem with the labels.They don't appears on the page. I can't figure out where is my mistake. For my it should be working fine. Any idea what's is wrong here? class RecForm (ModelForm): class Meta: model = Rec fields = ['name', 'kind',] labels = { 'name': 'Here put your name', } -
Form only displaying "Save" button
I want to make a textbox, that after I input some text into it, that text to be shown bellow that box, on the same page. But I only get the Save part and not the textbox, how can I fix this? My .html file: https://paste.pythondiscord.com/tivibaxiba.xml My views file: https://paste.pythondiscord.com/zavepigace.py -
How to use multiple username fields to authenticate a user in Django
I am working on a project where I can get a username, email, or phone number as a USERNAME_FIELD, similar to Instagram, but I am kinda stuck and don't really know how to do it, here is my USER model models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from .managers import UserManager class User(AbstractUser): username = models.CharField(max_length=150, unique=True) email = models.EmailField(_('email address'), unique=True) photo = models.ImageField(upload_to='avatars/', null=True, blank=True) last_updated = models.DateTimeField(null=True, blank=True) about = models.TextField(_( 'about'), max_length=500, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email def save(self, *args, **kwargs): self.last_updated = timezone.now() super(User, self).save(*args, **kwargs) managers.py from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import gettext_lazy as _ class UserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) … -
python: RpiMotorLib in virtual environment with Django - stepper motor is rotating jerky
I´m trying to run a stepper motor (NEMA17) with a DRV8225 stepper motor controller inside a python/Djano app in a virtual environment. The script for running the stepper motor with the RPiMotorLib is the script in this tutorial: https://makersportal.com/blog/raspberry-pi-stepper-motor-control-with-nema-17 When I run the script from command line inside/outside the virtual environment, the motor is rotating smooth. But if I run the script in my Django app, the motor is rotating jerky. In Django, I´m firing the script with a Django signal after updating the database: from django.db.models.signals import pre_save from django.dispatch import receiver from django.utils.crypto import get_random_string from django.utils.text import slugify from steppermotors.models import Steppermotor import RPi.GPIO as GPIO from RpiMotorLib import RpiMotorLib import time @receiver(pre_save, sender=Steppermotor) def run_steppermotor(sender, instance, *args, **kwargs): direction= 22 # Direction (DIR) GPIO Pin step = 23 # Step GPIO Pin EN_pin = 24 # enable pin (LOW to enable) # Declare a instance of class pass GPIO pins numbers and the motor type mymotortest = RpiMotorLib.A4988Nema(direction, step, (21,21,21), "DRV8825") GPIO.setup(EN_pin,GPIO.OUT) # set enable pin as output GPIO.output(EN_pin,GPIO.LOW) # pull enable to low to enable motor mymotortest.motor_go(False, # True=Clockwise, False=Counter-Clockwise "Full" , # Step type (Full,Half,1/4,1/8,1/16,1/32) instance.last_steps, # number of steps .0005, # step delay … -
Create object with multiple relations in graphene django
Hi guys I have the following models in my project class User(AbstractUser): email = models.EmailField(_('email address'), unique=True, blank=False, null=False) username = None first_name = None last_name = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] # set custom manager objects = UserManager() def __str__(self): return self.email class customer(models.Model): user = models.OneToOneField("users.User", verbose_name=_("customer user account"), on_delete=models.CASCADE) # general info first_name = models.CharField(_('customer first name'), max_length=100, help_text='customer first name') last_name = models.CharField(_('customer last name'), max_length=100, help_text='customer last name') # addresses info addresses = models.ManyToManyField('users.address', verbose_name=_('customer addresses'), related_name='customer_addresses', blank=True) default_shipping_address = models.ForeignKey('users.address', verbose_name=_('default shipping address'), on_delete=models.SET_NULL, null=True, blank=True, related_name='default_shipping') class address(models.Model): street_1 = models.CharField(_('street address 1'), max_length=250, help_text='street address one') street_2 = models.CharField(_('street address 2'), null=True, blank=True, max_length=250, help_text='street address two') postal_code = models.IntegerField(_('address zipcode'), help_text='address zipcode') city = models.CharField(_('address city'), max_length=100, help_text='address city') state = models.CharField(_('address state'), max_length=50, help_text='address state') country = models.CharField(_('address country'), max_length=100, help_text='address country') Here is my current implementation of creating a customer mutation class CreateCustomer(graphene.Mutation): customer = graphene.Field(CustomerType) class Arguments: email = graphene.String(required=True) first_name = graphene.String(required=True) last_name = graphene.String(required=True) password = graphene.String(required=True) phone = graphene.String(required=True) street_1 = graphene.String(required=False) street_2 = graphene.String(required=False) city = graphene.String(required=False) state = graphene.String(required=False) zipcode = graphene.String(required=False) country = graphene.String(required=False) def mutate(self, info, email, first_name, last_name, … -
Is there a way to give alert in django admin page for not matching some constraints while adding data in fields?
Basically in my simple website I add some college fest details like name, date etc. from admin page, not from the website. This is my Fest model class Fest(models.Model): FEST_CHOICES=[ ('CUL','Cultural'), ('TEC','Technical'), ('COL','College'), ('SPO','Sports'), ] id=models.IntegerField(primary_key=True) name=models.CharField(max_length=50) clg_id=models.ForeignKey(College,on_delete=models.CASCADE) fest_type=models.CharField(choices=FEST_CHOICES,default='COL',max_length=10) fest_desc=models.TextField(default='This is a fest') start_date=models.DateField(default='2022-01-01') end_date=models.DateField(default='2022-02-01') event_nos=models.IntegerField() org_id=models.ManyToManyField(Organizer) image=models.ImageField(default='default.jpg',upload_to='fest_pics') Currently for start_date and end_date I've given a check constraint under the model itself class Meta: constraints = [ CheckConstraint( check = Q(end_date__gte=F('start_date')), name = 'check_start_date', ) ] db_table='fest' But the problem is it redirects to a page showing IntegrityError, constraint is violated. How can I make it so that it gives an alert or message in admin page itself if end_date is lesser than start_date? -
Django: exists() using queryset cache
Does django's QuerySet.exists() method use the queryset's cache if called twice? For example # this makes a call to db queryset.exists() # > true # does it make a call to the db or reuse some cached result? queryset.exists() # > true I know that len(queryset) won't make a call to the db if it has previously been evaluated. Is it the same with exists? -
ckeditor image field customization
There is a model in which there is a field with a picture. these pictures will often change, I put ckeditor in order to have access to images on the server through the admin panel so as not to clog a lot of the same ones. But it doesn't look pretty. Maybe someone did something similar or used a different technology? models.py: class Action(models.Model): title = models.CharField(max_length=100) image = RichTextUploadingField(blank=True, null=True, config_name='custom') description = RichTextUploadingField() published = models.BooleanField(default=True) settings.py: CKEDITOR_CONFIGS = { 'default': { 'skin': 'moono', 'toolbar_Basic': [ ['Source', '-', 'Bold', 'Italic'] ], 'toolbar_YourCustomToolbarConfig': [ {'name': 'basicstyles', 'items': ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat']}, {'name': 'paragraph', 'items': ['NumberedList', 'BulletedList', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-']}, {'name': 'insert', 'items': ['Image', 'Table', 'Smiley', 'SpecialChar']}, '/', {'name': 'styles', 'items': ['Styles', 'Format', 'Font', 'FontSize']}, {'name': 'colors', 'items': ['TextColor', 'BGColor']}, ], 'toolbar': 'YourCustomToolbarConfig', 'tabSpaces': 4, }, 'custom': { 'skin': 'moono', 'toolbar_YourCustomToolbarConfig': [ {'name': 'insert', 'items': ['Image']}, ], 'toolbar': 'YourCustomToolbarConfig', } } enter image description here -
Django is supporting optional params in routes? [duplicate]
I've spend lot of time to find out how to create an url with optional params but I didn't find anything. I'm working wiht Python 3.4 This is my path and just I need to add an optional param: path('request', request_view.index, name="request_index"), Somthing like this one (like other lenguages): path('request/?status', request_view.index, name="request_index"), Any help? -
django: create user account for online shopping
I am developing an online ordering web, where user can place order by filling forms. After order is submitted, user can log in the account to view his own order information and status. My problem is, how to create such user account model and user account page that allow user to view only their orders? is there any good example and built-in functions available? -
how to integrate customizable bootstrap in Django
I am trying to add bootstrap files so that I can edit custom Saas. for the past 2 days I've been looking here and there but didn't seem to find the correct way, I have tried Webpack but that was too complex and it downloaded a lot of extra files that were not needed, I have tried installing via parcel, followed the official bootstrap documentation but didn't know how to integrate it with Django static files. I can not use cdn because I heard then you cant customize Saas. I have searched on youtube, but could not get 1 simple way. can you guys suggest me docs or video that provide a simple way so that I can customize Saas in my own way. i have researched alot. thank you -
Django: I have a TextField which when having text entered into it is also saving the html inputs
I am trying to get my HTML to return the information written to TextField, when the information is submitted and rendered instead of being seen in the expected format every new line the text would be on is appearing inside the angled paragraph brackets. can anyone help me understand why the text is being displayed like this, please? -
Steam social login with Django backend and React frontend
I have created a steam login with python-social-auth library on the backend. That was working fine. Now I am trying to separate my backend from the frontend using React for the frontend and Django for the backend. I can't seem to figure out or find anything on how do I connect the social login from React? I have followed this tutorial to do it which uses drf-social-oauth2-library but he is using a react-facebook-login package to make the login and retrieve the access token and refresh token for which I did not find anything similar for steam. I am really lost in here to what to do or how to go about it as I am quite new to both React and Django. -
Is it Apache 2.2 compatible with django3.2 and python 3.9?
Is it Apache 2.2 compatible with django3.2 and python 3.9? we have Apache 2.2 server needs to deploy python version 3.9 and Django 3.2. -
Django: Link to ForeignKey from change page
Imagine there are models: from django.db import models class Category(models.Model): name = models.CharField(...) class Product(models.Model): name = models.CharField(...) category = models.ForeignKey(Category, ...) Register models: from django.contrib import admin @admin.register(Product) class ProductAdmin(admin.ModelAdmin): fields = 'name', 'category', How could I make a category in product change page in admin to be a link to category by some built-in instruments? P.S. Well there is a package django-admin-relation-links. -
Django Rest Framework custom serializer data
I got a serializer response that looks like this: "results": [ { "property_name": "Villa", "username": "Ivan", "email": "ivan@mail.com", "start_date": "2022-01-05", "end_date": "2022-01-19" }, { "property_name": "Villa", "username": "Ivan", "email": "ivan@mail.com", "start_date": "2022-02-16", "end_date": "2022-03-03" }, { "property_name": "Villa", "username": "Ivan", "email": "ivan@mail.com", "start_date": "2022-02-11", "end_date": "2022-02-25" } ] I wonder is it possible for the serializer response to look like this: [ { name: 'Ivan', email: 'ivan@mail.com', stays: [ { "start_date": "2022-01-05", "end_date": "2022-01-19", "property_name: Villa" }, { "start_date": "2022-02-16", "end_date": "2022-03-03", "property_name: Villa" }, { "start_date": "2022-02-11", "end_date": "2022-02-25", "property_name: Villa" }, ] } ] This is my model: class PropertyReservation(BaseModelFields): start_date = models.DateField() end_date = models.DateField() property = models.ForeignKey('property.Property', on_delete=models.CASCADE) user = models.ForeignKey('user.UserModel', on_delete=models.CASCADE) my serializer: class PropertyReservationGuestSerializer(serializers.ModelSerializer): property_name = serializers.ReadOnlyField(source='property.name') username = serializers.ReadOnlyField(source='user.username') email = serializers.ReadOnlyField(source='user.email') class Meta: model = PropertyReservation fields = ('property_name', 'username', 'email', 'start_date', 'end_date') I tried a few things and cant manage the serializer response to look like one in the example above. This was the best answer I found on the internet Django RestFramework group by and still was not able to do it, on the first solution I got an error when I call the super() function: "super(type, obj): obj must … -
Putting "test" in URL breaks dispatcher in django [closed]
This is more a 'hmm' question rather than an "I need help" one So I have a URL like so: path('<str:movie>', views.movies, name='movies') The URL works just fine when I go to /movies/test-movie, but not movies/test or movies/bro Is there a certain reason why these URLs don't work? Thanks! -
How to use chained django_select2 selects in django admin panel?
I took almost unchanged guide from documentation there is my models.py from django.db import models class Country(models.Model): name = models.CharField(max_length=255) class City(models.Model): name = models.CharField(max_length=255) country = models.ForeignKey('Country', related_name="cities", on_delete=models.CASCADE) class Address(models.Model): country = models.ForeignKey('Country', on_delete=models.CASCADE) city = models.ForeignKey('City', on_delete=models.CASCADE) and have created ModelForm because simple Form from documentation guide is not fits for admin panel class AddressForm(forms.ModelForm): class Meta: model = Address fields = '__all__' widgets = { 'country': ModelSelect2Widget( model=Country, search_fields=['name__icontains'], ), 'city': ModelSelect2Widget( model=City, search_fields=['name__icontains'], dependent_fields={'country': 'country'}, max_results=500, ) } on the simple, not admin, page it works fine. I tried it just for testing. I really need only in admin panel. here is the template from docs <!DOCTYPE html> <html lang="en"> <head> <title>Create Book</title> {{ form.media.css }} <style> input, select {width: 100%} </style> </head> <body> <h1>Create a new Book</h1> <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit"> </form> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> {{ form.media.js }} </body> </html> and view class class AddressCreateView(generic.CreateView): model = models.Address form_class = forms.AddressForm success_url = "/" template_name = 'address.html' But in the admin panel the same form is not works. Selects does not containing any items and there is no search field shown there is also no requests sent to the …