K
K
k0r0g2022-02-10 16:11:58
Python
k0r0g, 2022-02-10 16:11:58

How to make friends django_select2 and admin?

Took a practically unchanged guide from the documentation to test:
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,
            )
        }


when I display the form on a regular page (I did it for verification, I just need to go to the admin panel) - the form works fine.
Sample:
<!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'


But when I try to use this form in the admin panel - the selects are empty and the search does not work
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)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question