6

I have a django site using the basic django registration framework. I have my login page working fine, but I want to change the css class on the inputs. The form passed to the login page looks to be an AuthenticationForm class.

What would be a good way to add a css class to the username, and password fields?

2 Answers 2

13

Sub class your auth form

forms.py

from django import forms
from django.contrib.auth.forms import AuthenticationForm
from django.forms.widgets import PasswordInput, TextInput

class RFPAuthForm(AuthenticationForm):
    username = forms.CharField(widget=TextInput(attrs={'class': 'span2','placeholder': 'Email'}))
    password = forms.CharField(widget=PasswordInput(attrs={'class': 'span2','placeholder':'Password'}))
Sign up to request clarification or add additional context in comments.

2 Comments

Also try github.com/kmike/django-widget-tweaks if you just need to add a class.
The username field in the AuthenticationForm has got max_langth=254 specified. Do you think I should add this value to my field too? Are those overwritten by my declaration?
8

I do what you want like this:

def login(request):
    form = AuthenticationForm(request)
    form.fields['username'].widget.attrs['class'] = "custom_css"
    form.fields['password'].widget.attrs['style'] = "background:red"
    return render_to_response("login.html", {'form':form},
                          context_instance=RequestContext(request))

3 Comments

What if I am using django.contrib.auth.views.login and I want to include the form on every page in my website? I cannot see the login form I included in base.html and I think it is because I cannot connect the django.contrib.auth.views.login's AuthenticationForm to my CSS file. What do you think?
1. you can make a template tag, something like {% get_login_form %}
2. you can extend the auth form and overwrite the init method to put the attrs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.