forms.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. from django import forms
  2. from django.contrib.auth.models import User
  3. from django.core.exceptions import ValidationError
  4. from django.utils.translation import ugettext_lazy as _
  5. class SignUpForm(forms.Form):
  6. '''
  7. Each field (both passwords at once in their case) is checked with it's own function as
  8. by doing so all can be checked at once for errors and have errors thrown simultaneously.
  9. If the user happens to enter an email that already exists as well as a username that already
  10. exists and the two passwords don't match, then the user will be notified of all three errors
  11. without having to perform three correct_error - submit - read_error cycles
  12. '''
  13. name = forms.CharField()
  14. email = forms.EmailField()
  15. password = forms.CharField(max_length = 50, min_length = 8, widget = forms.PasswordInput)
  16. password2 = forms.CharField(max_length = 50, min_length = 8, widget = forms.PasswordInput)
  17. # clean passwords, two fields can't be declared as above
  18. def clean(self):
  19. cleanName = self.cleaned_data['name']
  20. nameExists = User.objects.filter(username = cleanName).count()
  21. if nameExists > 0 :
  22. raise ValidationError(_('Username already exists. Please try a different one.'))
  23. mail = self.cleaned_data['email']
  24. emailExists = User.objects.filter(email = mail).count()
  25. if emailExists > 0 :
  26. raise ValidationError(_('An account already exists with the email provided. Please use a different email address, or log in.'))
  27. p1 = self.cleaned_data.get('password')
  28. p2 = self.cleaned_data.get('password2')
  29. if (p1 != p2):
  30. raise ValidationError(_('Passwords do not match.'))
  31. return self.cleaned_data