Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In login.html I have:

 <form class="login" method="POST" action="{% url 'account_login' %}">
  {% csrf_token %}

  {{form.as_p}}

How in the world can I add custom css classes and other atributes to the fields? Nobody on the internet seems to have had this problem before. I just need to add something as simple as a class. Thanks in advance if someone answers this. I really hope this will be helpful for someone else.

like image 592
Camilo Sanchez Avatar asked Jan 26 '14 20:01

Camilo Sanchez


2 Answers

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'})
like image 125
andrea.ge Avatar answered Sep 30 '22 16:09

andrea.ge


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.

like image 33
Moving.Paper Avatar answered Sep 30 '22 18:09

Moving.Paper