About Django Autocomplete Light with Forwarding and Django Crispy Forms

django-crispy-forms overwrites the default field rendering, so to make the field forwarding of django-autocomplete-light work with django-crispy-forms, you need to call the rendering of forward configuration in the layout manually:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# shops/forms.py
from django import forms
from django.utils.translation import gettext_lazy as _
from crispy_forms.helper import FormHelper
from crispy_forms import layout
from dal import autocomplete
from .models import Country, City

class ShopLocationForm(forms.Form):
    country = forms.ModelChoiceField(
        queryset=Country.objects.all(),
        widget=autocomplete.ModelSelect2(
            url="country-autocomplete",
        )
    )
    city = forms.ModelChoiceField(
        queryset=City.objects.all(),
        widget=autocomplete.ModelSelect2(
            url="city-autocomplete",
            forward=["country"],
        )
    )
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_action = reverse_lazy("shop_location_form")
        self.helper.form_method = "POST"
        self.helper.layout = layout.Layout(
            layout.Field("country"),
            layout.Field("city"),
            layout.HTML(
                self.fields["city"].widget.render_forward_conf("id_city")
            ),
            layout.Submit("save", _("Save")),
        )

See the rest of the code in the trick About Dependent Autocompletes.

Tips and Tricks Programming Django 5.x Django 4.2 Django 3.2 django-crispy-forms django-autocomplete-light