Valter Silva
Valter Silva

Reputation: 16656

How to use CSS with Django forms?

I have a HTML and CSS template done already, and now I have to use Python and Django to give life to the system. But I stuck into something: how to use my css with django forms ?

For example, this is what I have use in Django:

<label for="id_username">Username:</label>
{{ form.username }}

And this is what django generates:

<input id="id_username" maxlength="100" name="username" type="text" />

As the fields in the form are automatically generated by django, how can I apply style for the input field and the others fields too ? This is my login form for example and I would like to use django with the css done so far, but how ?

<form class="form-signin" action="" method="post">
  <h2 class="form-signin-heading">Pydorado</h2>
    <div class="login-wrap">
      <div class="user-login-info">
        <input type="text" class="form-control" placeholder="User ID" autofocus>
        <input type="password" class="form-control" placeholder="Password">
      </div>
      //..
    </div>
</form>

I read the django documentation related to this but I couldn't find any solution so far. Any idea or suggestions ?

Upvotes: 1

Views: 176

Answers (1)

Jonathan
Jonathan

Reputation: 8890

You can apply your styles in the formfield by adding extra attributes like this:

myfield = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))

I also saw a neat solution where someone created a custom template tag where you could add classes in the template itself.

Upvotes: 4

Related Questions