Rakesh K
Rakesh K

Reputation: 8505

Adding styles to django.forms controls using Bootstrap

I have a form in my HTML page which I am generating using Django's forms.Form class. I would like to apply styles to the html controls that get generated using Bootstrap. I found that Bootstrap applies styles to the form controls if they have certain class attribute e.g. form-control. I am including the form object in my template using form.as_p directive. Since there are no explicit html controls that I write in my html page, I don't know how to include the class attribute so that the styles are applied. Can you please help me solve this problem so that I can apply the Bootstrap styles to my form controls?

Thanks, Rakesh.

Upvotes: 1

Views: 89

Answers (3)

cor
cor

Reputation: 3393

You can define it with the widget. For example:

class SearchForm(forms.Form):
    q=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Search'}))

Another example using a ModelForm:

class SearchForm(ModelForm):
    class Meta:
        model = SearchField
        fields = ['name']
        widgets = {
            'name' = forms.TextInput(attrs={'class':'form-control'})
        }

Upvotes: 0

Muhammad Saeed Arabi
Muhammad Saeed Arabi

Reputation: 66

You can also specify the widget's class in the Form's __init__ like the following. This is useful when you have a ModelForm and you don't want to override the default widgets or fields.

class SearchForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(SearchForm, self).__init__(*args, **kwargs)
        self.fields['q'].widget.attrs = {'class': 'form-control'}

    class Meta:
        model = SearchQuery
        fields = ('q',)

Upvotes: 0

The easiest way I found to handle this is using crispy-forms.

Upvotes: 1

Related Questions