How to add css attributes to ModelChoiceField in Django?

23 Views Asked by At

Want to design the form for adding products, but fail in adding css atributes to the ModelChoicefield. For the CharField it can be easly done, but the ModelChoicefield is not accepting 'attrs', same with its widget.

is there a way to add attributes 'placeholder' and 'class' without redefining the ModelChoiceField and its widget?

class ProductAddForm(forms.ModelForm):

    product_group = forms.ModelChoiceField(
        queryset=ProductGroup.objects.all().order_by('group_name').order_by('to_parent'),
        empty_label='group',
        label='Group',
    )
    bar_code = forms.CharField(
        widget=forms.TextInput(
            attrs={'placeholder': "bar code", 'class': "form-control-class",}
        ),
    )
1

There are 1 best solutions below

1
Aliaksandr On

Just add:

widget=forms.Select(attrs={'type': "text",'class': "form-control"})