You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

forms.py 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import string
  2. import random
  3. from django.contrib.auth.forms import AuthenticationForm
  4. from django.utils.translation import ugettext_lazy as _
  5. from django import forms
  6. from django.contrib.auth.models import User
  7. from django.contrib.auth import authenticate
  8. def generate_username():
  9. uname = ''.join([random.choice(string.letters + string.digits + '_') for i in range(30)])
  10. try:
  11. User.objects.get(username=uname)
  12. return generate_username()
  13. except User.DoesNotExist:
  14. return uname
  15. class EmailAuthenticationForm(AuthenticationForm):
  16. """
  17. Extends the standard django AuthenticationForm, to support 75 character
  18. usernames. 75 character usernames are needed to support the EmailOrUsername
  19. auth backend.
  20. """
  21. username = forms.EmailField(label=_('Email Address'))
  22. class EmailUserCreationForm(forms.ModelForm):
  23. email = forms.EmailField(label=_('Email Address'))
  24. password1 = forms.CharField(label=_('Password'), widget=forms.PasswordInput)
  25. password2 = forms.CharField(label=_('Confirm Password'), widget=forms.PasswordInput)
  26. class Meta:
  27. model = User
  28. fields = ('email', )
  29. def clean_email(self):
  30. email = self.cleaned_data['email']
  31. try:
  32. User.objects.get(email=email)
  33. except User.DoesNotExist:
  34. return email
  35. raise forms.ValidationError(_("A user with that email address already exists."))
  36. def clean_password2(self):
  37. password1 = self.cleaned_data.get('password1', '')
  38. password2 = self.cleaned_data.get('password2', '')
  39. if password1 != password2:
  40. raise forms.ValidationError(_("The two password fields didn't match."))
  41. return password2
  42. def save(self, commit=True):
  43. user = super(EmailUserCreationForm, self).save(commit=False)
  44. user.set_password(self.cleaned_data['password1'])
  45. user.username = generate_username()
  46. if commit:
  47. user.save()
  48. return user