15👍
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' }}