Взял практически неизменным гайд из документации, чтобы протестить:
models.py
from django.db import models
class Country(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class City(models.Model):
name = models.CharField(max_length=255)
country = models.ForeignKey('Country', related_name="cities", on_delete=models.CASCADE)
def __str__(self):
return self.name
class Address(models.Model):
country = models.ForeignKey('Country', on_delete=models.CASCADE)
city = models.ForeignKey('City', on_delete=models.CASCADE)
def __str__(self):
return f'{self.country}__{self.city}'
forms.py
from django import forms
from django_select2.forms import ModelSelect2Widget
from .models import Address, City, Country
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,
)
}
когда вывожу форму на обычную страницу (для проверки сделал, так-то мне только в админку надо) - форма работает нормально.
Шаблон:
<!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>
View
class AddressCreateView(generic.CreateView):
model = models.Address
form_class = forms.AddressForm
success_url = "/"
template_name = 'address.html'
Но когда пытаюсь использовать эту форму в админке - select'ы оказываются пустыми и поиск не работает
from django.contrib import admin
from .models import City, Country, Address
from .forms import AddressForm
@admin.register(Address)
class AddressAdmin(admin.ModelAdmin):
class Media:
js = (
'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js',
)
form = AddressForm
admin.site.register(City)
admin.site.register(Country)