I am using Django's authentication backend and it works fine, but I want to give the username and password fields a custom CSS class. I have been trying to look for a solution but I cannot find anything here or anywhere else. This is what I have done so far:
project/forms.py:
from django import forms
from django.contrib.auth.forms import AuthenticationForm
class LoginForm(AuthenticationForm):
username = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control form-control-lg'}))
password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control form-control-lg'}))
project/urls.py:
from django.contrib import admin
from django.urls import path, include
from .forms import LoginForm
urlpatterns = [
path('accounts/', include('django.contrib.auth.urls'), {'authentication_form': LoginForm}),
]
accounts/login.html:
<form method="POST">
{% csrf_token %}
<div class="form-group">
{{ form.username }}
{{ form.password }}
<button type="submit" class="btn btn-primary btn-lg btn-block">Sign in</button>
</form>
The login system works but I cannot get the CSS changes to show up. I inspected the username and password fields but they are not showing up in the browser at all. I am guessing I am missing something somewhere?
Not sure how you can do it directly, but I use widget-tweaks to do that, and it works beautifully (also does all the error notification). You don't need to set anything in the form, everything is done in the template. The line in the template would then be:
{% with "form-control input-field-"|add:form.username.name as field_class %}{% render_field form.username class=field_class %}{% endwith %}
That would give you a separate class for every input field. Have a look at https://github.com/jazzband/django-widget-tweaks.