D
D
DjangoIsFree2014-09-26 22:12:57
Django
DjangoIsFree, 2014-09-26 22:12:57

How to apply css styles to form fields in django?

For example, there is a form with a text field:

class TextForm(forms.Form):
    body = forms.CharField(max_length=100)

and its representations in the template:
<form method="post">                   
    {{ form.body }}
</form>

Question: how to apply css styles to this field, for example, as in this input tag?
<form method="post">    
    <input type="text" class="form-control" placeholder="type text">
</form>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
mefisto, 2014-09-27
@DjangoIsFree

For example like this

class TextForm(forms.Form):
    body = forms.CharField(max_length=100)
    def __init__(self, *args, **kwargs):
        super(TextForm, self).__init__(*args, **kwargs)
        self.fields['body'].widget.attrs.update({'class': 'form-control'})

A
Alexey Bukin, 2014-09-30
@abukin

If the form needs to be "bootstrap", then it is better to use https://pypi.python.org/pypi/django-forms-bootstrap , it adds exactly those classes.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question