About Model Choice Fields using Models with Slugs

Use the to_field_name attribute for forms.ModelChoiceField and forms.ModelMultipleChoiceField if you want to operate with fields other than the primary key.

1
2
3
4
5
6
7
class TagFilterForm(forms.Form):
    tags = forms.ModelMultipleChoiceField(
        label=_("Tags"),
        queryset=Tag.objects.all(),
        to_field_name="slug",
        required=False,
    )

Tips and Tricks Programming Django 4.2 Django 3.2 Django 2.2