PageRenderTime 89ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 0ms

/registration/forms.py

https://bitbucket.org/andrewlvov/django-registration-custom
Python | 120 lines | 100 code | 5 blank | 15 comment | 1 complexity | e6108465f0535ab954ba622e8e7c8391 MD5 | raw file
  1. """
  2. Forms and validation code for user registration.
  3. Note that all of these forms assume Django's bundle default ``User``
  4. model; since it's not possible for a form to anticipate in advance the
  5. needs of custom user models, you will need to write your own forms if
  6. you're using a custom model.
  7. """
  8. from django.contrib.auth.models import User
  9. from django import forms
  10. from django.utils.translation import ugettext_lazy as _
  11. class RegistrationForm(forms.Form):
  12. """
  13. Form for registering a new user account.
  14. Validates that the requested username is not already in use, and
  15. requires the password to be entered twice to catch typos.
  16. Subclasses should feel free to add any additional validation they
  17. need, but should avoid defining a ``save()`` method -- the actual
  18. saving of collected user data is delegated to the active
  19. registration backend.
  20. """
  21. required_css_class = 'required'
  22. username = forms.RegexField(regex=r'^[\w.@+-]+$',
  23. max_length=30,
  24. label=_("Username"),
  25. error_messages={'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")})
  26. email = forms.EmailField(label=_("E-mail"))
  27. password1 = forms.CharField(widget=forms.PasswordInput,
  28. label=_("Password"))
  29. password2 = forms.CharField(widget=forms.PasswordInput,
  30. label=_("Password (again)"))
  31. def clean_username(self):
  32. """
  33. Validate that the username is alphanumeric and is not already
  34. in use.
  35. """
  36. existing = User.objects.filter(username__iexact=self.cleaned_data['username'])
  37. if existing.exists():
  38. raise forms.ValidationError(_("A user with that username already exists."))
  39. else:
  40. return self.cleaned_data['username']
  41. def clean(self):
  42. """
  43. Verifiy that the values entered into the two password fields
  44. match. Note that an error here will end up in
  45. ``non_field_errors()`` because it doesn't apply to a single
  46. field.
  47. """
  48. if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
  49. if self.cleaned_data['password1'] != self.cleaned_data['password2']:
  50. raise forms.ValidationError(_("The two password fields didn't match."))
  51. return self.cleaned_data
  52. class RegistrationFormTermsOfService(RegistrationForm):
  53. """
  54. Subclass of ``RegistrationForm`` which adds a required checkbox
  55. for agreeing to a site's Terms of Service.
  56. """
  57. tos = forms.BooleanField(widget=forms.CheckboxInput,
  58. label=_(u'I have read and agree to the Terms of Service'),
  59. error_messages={'required': _("You must agree to the terms to register")})
  60. class RegistrationFormUniqueEmail(RegistrationForm):
  61. """
  62. Subclass of ``RegistrationForm`` which enforces uniqueness of
  63. email addresses.
  64. """
  65. def clean_email(self):
  66. """
  67. Validate that the supplied email address is unique for the
  68. site.
  69. """
  70. if User.objects.filter(email__iexact=self.cleaned_data['email']):
  71. raise forms.ValidationError(_("This email address is already in use. Please supply a different email address."))
  72. return self.cleaned_data['email']
  73. class RegistrationFormNoFreeEmail(RegistrationForm):
  74. """
  75. Subclass of ``RegistrationForm`` which disallows registration with
  76. email addresses from popular free webmail services; moderately
  77. useful for preventing automated spam registrations.
  78. To change the list of banned domains, subclass this form and
  79. override the attribute ``bad_domains``.
  80. """
  81. bad_domains = ['aim.com', 'aol.com', 'email.com', 'gmail.com',
  82. 'googlemail.com', 'hotmail.com', 'hushmail.com',
  83. 'msn.com', 'mail.ru', 'mailinator.com', 'live.com',
  84. 'yahoo.com']
  85. def clean_email(self):
  86. """
  87. Check the supplied email address against a list of known free
  88. webmail domains.
  89. """
  90. email_domain = self.cleaned_data['email'].split('@')[1]
  91. if email_domain in self.bad_domains:
  92. raise forms.ValidationError(_("Registration using free email addresses is prohibited. Please supply a different email address."))
  93. return self.cleaned_data['email']