Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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
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

This comment has been minimized.

Copy link

@michelepeixoto michelepeixoto commented May 21, 2018

Nice, thanks!

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