Created
October 28, 2012 00:22
-
-
Save pije76/3967012 to your computer and use it in GitHub Desktop.
Django Login Form
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class NextUrlField(forms.CharField): | |
widget = forms.HiddenInput | |
def __init__(self, *args, **kwargs): | |
super(NextUrlField, self).__init__(*args, **kwargs) | |
self.required = False | |
def clean(self, value): | |
if not value: | |
return getattr(settings, 'LOGIN_REDIRECT_URL', '/') | |
else: | |
return value | |
class LoginForm(forms.Form): | |
username = User._meta.get_field('username').formfield() | |
password = User._meta.get_field('password').formfield(widget=forms.PasswordInput) | |
next = NextUrlField() | |
def __init__(self, *args, **kwargs): | |
self.request = kwargs.pop('request') | |
self.base_fields['username'].help_text = '' | |
#self.base_fields['password'].widget = forms.PasswordInput() | |
self.base_fields['password'].help_text = '' | |
self.base_fields['next'] = NextUrlField() | |
super(LoginForm, self).__init__(*args, **kwargs) | |
def clean(self): | |
super(LoginForm, self).clean() | |
if self.is_valid(): | |
user = authenticate( | |
username=self.cleaned_data['username'], | |
password=self.cleaned_data['password']) | |
if not user is None: | |
if user.is_active: | |
login(self.request, user) | |
return self.cleaned_data | |
else: | |
raise forms.ValidationError(_("Sorry. Your account is not active. Most likely is that you didn't confirm your registration")) | |
else: | |
raise forms.ValidationError(_('Wrong username or password')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment