Tobi
Tobi

Reputation: 351

Django: custom widgets in custom modelchoicefield

I am using a custom Modelchoicefield class in order to get the full names of a part of the users group rather than their usernames:

class UserModelChoiceField(forms.ModelChoiceField):
    def label_from_instance(self, obj):
        return "%s" % (obj.get_full_name())

In the form, I then call this class before defining widgets for the other fields in "class Meta":

tutor = UserModelChoiceField(User.objects.filter(groups__name='teachers'))

Is there a way to add a widget to the "tutor"-field? I would like to add "class='form-control'" to the HTML output.

Thanks, Tobi

Upvotes: 1

Views: 2063

Answers (1)

mariodev
mariodev

Reputation: 15484

I think that will do:

tutor = UserModelChoiceField(
    User.objects.filter(groups__name='teachers')
    widget=Select(attrs={'class': 'form-control'})
)

Although if you're gonna use bootstrap in more places, you should consider crispy-forms or similar library.

Upvotes: 1

Related Questions