About Comboboxes in Django Forms

A combobox is a graphical user interface element that combines an editable text input field with a drop-down list. In Django forms you can create one using django-autocomplete-light as follows:

 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
from django import forms
from django.urls import reverse_lazy
from django.utils.translation import gettext_lazy
from dal import autocomplete
from dal_select2.widgets import Select2
from .models import Profile

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = "__all__"

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        COLOR_CHOICES = [
            ("red", _("Red")),
            ("green", _("Green")),
            ("blue", _("Blue")),
        ]
        if self.instance and self.instance.bg_color not in dict(COLOR_CHOICES):
            COLOR_CHOICES = [
                (self.instance.bg_color, self.instance.bg_color)
            ] + COLOR_CHOICES

        self.fields["bg_color"] = forms.CharField(
            label=_("Cover background color"),
            widget=Select2(choices=COLOR_CHOICES, attrs={"data-tags": 1}),
            required=False,
        )

Tips and Tricks User Experience Development django-autocomplete-light