Django Allauth - How to add custom css class to fields?

You can overwrite the default LoginForm using ACCOUNT_FORMS in your settings.py, for example:

ACCOUNT_FORMS = {'login': 'yourapp.forms.YourLoginForm'}

and write a YourLoginForm accordingly.

# yourapp/forms.py

from allauth.account.forms import LoginForm

class YourLoginForm(LoginForm):
    def __init__(self, *args, **kwargs):
        super(YourLoginForm, self).__init__(*args, **kwargs)
        self.fields['login'].widget = forms.TextInput(attrs={'type': 'email', 'class': 'yourclass'})
        self.fields['password'].widget = forms.PasswordInput(attrs={'class': 'yourclass'})

A little hacky way to do it- but it works: Get from your console the html for the form as it is generated from {{ form.as_p }} paste it somewhere in reach. Now build your own form. with inputs and all the classes you need. For each input field in your new all classed up form- get the ID as it is written in the original form. This should make the form work. make sure you have all the inputs- including hidden ones the {{ form.as_p }} generates (not the csrf!)

Finally to show errors: for each field insert {{ form.fieldname.errors }} make sure your field name is as in the original form.

All done.


You are using the HTML Django creates for you by calling form.as_p just like this example.

What you might be looking for is the example right below it. Where you write more of the markup in the template.

It sounds like you might also be interested in this. Creating your form and specifying the classes to be added to the field using something like:

myfield = forms.CharField(
            widget=forms.TextInput(attrs={'class':'myclass'}))

Now calling form.myfield in the template will create an input text field with the class myclass on it.