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:
# 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
Also by me
Django Paddle Subscriptions app
For Django-based SaaS projects.
Django GDPR Cookie Consent app
For Django websites that use cookies.