1

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.

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

That would be my answer to. Don't be a fool, use a tool :)
0

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'})
        }

1 Comment

I have declared the fields of my form using 'model=MyModel' statement in the Meta class of the form class. How do I add the attributes in this case?
0

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',)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.