Skip to content

Instantly share code, notes, and snippets.

@chriskief
Created October 24, 2013 01:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chriskief/7129979 to your computer and use it in GitHub Desktop.
Save chriskief/7129979 to your computer and use it in GitHub Desktop.
from django import forms
from app.models import User
from django.contrib.auth.hashers import check_password
from django.db.models import Q
class SignInForm(forms.Form):
username = forms.CharField(max_length=User._meta.get_field('email').max_length)
password = forms.CharField(min_length=6, max_length=16, widget=forms.PasswordInput())
go = forms.CharField(required=False, max_length=50, widget=forms.HiddenInput())
def is_valid(self):
# run the parent validation first
valid = super(SignInForm, self).is_valid()
# we're done now if not valid
if not valid:
return valid
# so far so good, get this user based on the username or email
try:
user = User.objects.get(
Q(username=self.cleaned_data['username']) | Q(email=self.cleaned_data['username'])
)
# no user with this username or email address
except User.DoesNotExist:
self._errors['no_user'] = 'User does not exist'
return False
# verify the passwords match
if not check_password(self.cleaned_data['password'], user.password):
self._errors['invalid_password'] = 'Password is invalid'
return False
# all good
return True
@michelepeixoto
Copy link

Nice, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment