Django - Subclass the default AuthenticationForm
I can use the default Django AuthenticationForm (or any Django's built-in forms), it's enough in most cases. But, for some reasons, I want to add style for the login form. So, I use the following method to add "class" and "placeholder" attributes for username and password inputs:
1. Create .../myapp/forms.py:
from django import forms
from django.contrib.auth.forms import AuthenticationForm
class MyAuthenticationForm(AuthenticationForm):
def __init__(self, *args, **kwargs):
super(MyAuthenticationForm, self).__init__(*args, **kwargs)
self.base_fields['username'].widget.attrs['class'] = 'form-control'
self.base_fields['username'].widget.attrs['placeholder'] = 'Username'
self.base_fields['password'].widget.attrs['class'] = 'form-control'
self.base_fields['password'].widget.attrs['placeholder'] = 'Password'
2. Modify the urls.py:
from django.conf.urls import patterns, include, url
from myproject.myapp.forms import MyAuthenticationForm
...
urlpatterns = patterns('',
...
url(r'^accounts/login/?$','django.contrib.auth.views.login',{'template_name': 'login.html', \
'authentication_form': MyAuthenticationForm}),
)
And when the authentication form is rendered in login.html, the username and password inputs will have class and placeholder attributes.
1. Create .../myapp/forms.py:
from django import forms
from django.contrib.auth.forms import AuthenticationForm
class MyAuthenticationForm(AuthenticationForm):
def __init__(self, *args, **kwargs):
super(MyAuthenticationForm, self).__init__(*args, **kwargs)
self.base_fields['username'].widget.attrs['class'] = 'form-control'
self.base_fields['username'].widget.attrs['placeholder'] = 'Username'
self.base_fields['password'].widget.attrs['class'] = 'form-control'
self.base_fields['password'].widget.attrs['placeholder'] = 'Password'
2. Modify the urls.py:
from django.conf.urls import patterns, include, url
from myproject.myapp.forms import MyAuthenticationForm
...
urlpatterns = patterns('',
...
url(r'^accounts/login/?$','django.contrib.auth.views.login',{'template_name': 'login.html', \
'authentication_form': MyAuthenticationForm}),
)
And when the authentication form is rendered in login.html, the username and password inputs will have class and placeholder attributes.
Comments
Post a Comment