[Django]-Django ModelForm widgets and labels

3👍

widgets and labels are for overriding the relevant attributes of fields created automatically from the model. But in the case of field_z, it’s not being created automatically; you’ve specifically supplied a definition. So you need to set the relevant attributes directly in that definition:

class MyComplicatedModelForm(forms.ModelForm):
    field_z = forms.ModelChoiceField(
        queryset=AnyClass.objects.all(),
        empty_label=None,
        required=True,
        to_field_name='id',
        label='Select your Z value here',
        widget=forms.SelectMultiple(attrs={'class': 'myclass'})
    )

    class Meta:
        model = MyComplicatedModel
        fields = ['field_z']

Note that ModelChoiceField is a field, not a widget, so wouldn’t work in widgets anyway – the relevant widget is SelectMultiple.

Leave a comment