PageRenderTime 102ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/~apps/registration/forms.py

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