Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a class atribute to django auth login form?

I've just installed Django's default authentication app. It is working and everything but I am wondering how I could change the CSS of the form.

Say I have this:

<form ...>
    <input type="text" class="input-class" placeholder="user">
    <input type="submit" value="login" />
</form>

...which would show a pretty form following the class in the text input.

But currently I have the simple ugly login.html template for Django auth:

<form method="post" action="{% url 'login' %}">
{% csrf_token %}

<div>
   <td>{{ form.username.label_tag }}</td>
   <td>{{ form.username }}</td>
</div>

What I want to do is to get the second form with the CSS classes of the first.

Is there a way of doing so without messing with models and forms? And, if not, can someone please show me the way?

Thank you very much.

like image 276
Berbus Avatar asked Sep 16 '25 09:09

Berbus


1 Answers

I wish there was a straightforward way to do it, without messing with forms or installing a third-party app. But, unfortunately, that's not the case.

If you don't want to install any app, you could extend the AuthenticationForm:

class PrettyAuthenticationForm(AuthenticationForm):
    class Meta:
        widgets = {
            'username': forms.TextInput(attrs={'class': 'input-class'})
        }

Then, if you are using the LoginView, pass your new PrettyAuthenticationForm using the authentication_form parameter (see the link for more details).

But I don't know if it's worth all the trouble. I've done it a few times, but usually I prefer installing django-widget-tweaks or django-crispy-forms.

If you only need to add some css class here and there, and you are using a custom css set, I would suggest using the django-widget-tweaks.

If you have several forms, and you are using some CSS framework like Bootstrap or Foundation, I would recommend using django-crispy-forms.

An example with django-widget-tweaks, first install it:

pip install django-widget-tweaks

Add it do your settings.py

INSTALLED_APPS = [
    # ...

    'widget_tweaks',
]

In your template, load it on top of the file:

{% load widget_tweaks %}

Then use it on your fields:

{{ form.username|add_class:'input-class' }}
like image 105
Vitor Freitas Avatar answered Sep 18 '25 08:09

Vitor Freitas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!