widgets for ChoiceField in modelform

Viewed 204

I'm using a modelform for my form Post and I'm using a bootstrap starter code as my base.html but because I use the {% csrf_token %} {{form.as_p}} on my add_blog page, bootstrap doesn't work and because of that it needs class='form-control', I have managed to do that on all of my fields but Choice input, if I do include my author(choicefield) in the widgets I get a TypeError: init() got an unexpected keyword argument 'attrs'

class PostForm(forms.ModelForm):
class Meta:

    model = Post
    fields = ("title", "title_tag", "author", "body")
    widget = forms.Select(attrs={"class": "form-control"})

    widgets = {
        'title': TextInput(attrs={'class': 'form-control'}),
        'title_tag': TextInput(attrs={'class': 'form-control'}),
        'body': Textarea(attrs={'class': 'form-control'}),
        'author': ChoiceField(attrs={'class': 'form-control'})


    }
1 Answers

A ChoiceField [Django-doc] is a form field, not a form widget. The default widget of a ChoiceField is a Select [Django-doc]. You thus can specify to use this widget with:

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ('title', 'title_tag', 'author', 'body')

        widgets = {
            'title': TextInput(attrs={'class': 'form-control'}),
            'title_tag': TextInput(attrs={'class': 'form-control'}),
            'body': Textarea(attrs={'class': 'form-control'}),
            'author': Select(attrs={'class': 'form-control'})
        }
Related