Skip to content

Commit 345fc5d

Browse files
committed
add new forms example
1 parent ea287c0 commit 345fc5d

File tree

1 file changed

+121
-0
lines changed

1 file changed

+121
-0
lines changed

content/pages/examples/django/django-forms.markdown

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -734,3 +734,124 @@ def to_bool(value):
734734
else:
735735
raise ValidationError("Invalid Boolean Value.")
736736
```
737+
738+
739+
## Example 5 from django-registration (redux)
740+
[django-registration (redux)](https://github.com/macropin/django-registration)
741+
([project documentation](https://django-registration-redux.readthedocs.io/en/latest/))
742+
is a [Django](/django.html) code library for one-phase, two-phase and
743+
three-phase registration flows. The code is available
744+
[open source](https://github.com/macropin/django-registration/blob/master/LICENSE).
745+
746+
[**django-registration / registration / forms.py**](https://github.com/macropin/django-registration/blob/master/registration/forms.py)
747+
748+
```python
749+
"""
750+
Forms and validation code for user registration.
751+
Note that all of these forms assume Django's bundle default ``User``
752+
model; since it's not possible for a form to anticipate in advance the
753+
needs of custom user models, you will need to write your own forms if
754+
you're using a custom model.
755+
"""
756+
from __future__ import unicode_literals
757+
758+
~~from django import forms
759+
~~from django.contrib.auth.forms import UserCreationForm
760+
from django.utils.translation import ugettext_lazy as _
761+
762+
from .users import UserModel
763+
from .users import UsernameField
764+
765+
User = UserModel()
766+
767+
768+
~~class RegistrationForm(UserCreationForm):
769+
"""
770+
Form for registering a new user account.
771+
Validates that the requested username is not already in use, and
772+
requires the password to be entered twice to catch typos.
773+
Subclasses should feel free to add any additional validation they
774+
need, but should avoid defining a ``save()`` method -- the actual
775+
saving of collected user data is delegated to the active
776+
registration backend.
777+
"""
778+
required_css_class = 'required'
779+
~~ email = forms.EmailField(label=_("E-mail"))
780+
781+
class Meta:
782+
model = User
783+
fields = (UsernameField(), "email")
784+
785+
786+
class RegistrationFormUsernameLowercase(RegistrationForm):
787+
"""
788+
A subclass of :class:`RegistrationForm` which enforces unique
789+
case insensitive usernames, make all usernames to lower case.
790+
"""
791+
def clean_username(self):
792+
username = self.cleaned_data.get('username', '').lower()
793+
if User.objects.filter(**{UsernameField(): username}).exists():
794+
~~ raise forms.ValidationError(_\
795+
~~ ('A user with that username already exists.'))
796+
797+
return username
798+
799+
800+
class RegistrationFormTermsOfService(RegistrationForm):
801+
"""
802+
Subclass of ``RegistrationForm`` which adds a required checkbox
803+
for agreeing to a site's Terms of Service.
804+
"""
805+
~~ tos = forms.BooleanField(widget=forms.CheckboxInput,
806+
~~ label=_('I have read and agree to the Terms of Service'),
807+
~~ error_messages={'required': _\
808+
~~ ("You must agree to the terms to register")})
809+
810+
811+
class RegistrationFormUniqueEmail(RegistrationForm):
812+
"""
813+
Subclass of ``RegistrationForm`` which enforces uniqueness of
814+
email addresses.
815+
"""
816+
def clean_email(self):
817+
"""
818+
Validate that the supplied email address is unique for the
819+
site.
820+
"""
821+
if User.objects.filter(email__iexact=self.cleaned_data['email']):
822+
~~ raise forms.ValidationError(_\
823+
~~ ("This email address is already in use. " + \
824+
~~ "Please supply a different email address."))
825+
return self.cleaned_data['email']
826+
827+
828+
class RegistrationFormNoFreeEmail(RegistrationForm):
829+
"""
830+
Subclass of ``RegistrationForm`` which disallows registration with
831+
email addresses from popular free webmail services; moderately
832+
useful for preventing automated spam registrations.
833+
To change the list of banned domains, subclass this form and
834+
override the attribute ``bad_domains``.
835+
"""
836+
bad_domains = ['aim.com', 'aol.com', 'email.com', 'gmail.com',
837+
'googlemail.com', 'hotmail.com', 'hushmail.com',
838+
'msn.com', 'mail.ru', 'mailinator.com', 'live.com',
839+
'yahoo.com', 'outlook.com']
840+
841+
def clean_email(self):
842+
"""
843+
Check the supplied email address against a list of known free
844+
webmail domains.
845+
"""
846+
email_domain = self.cleaned_data['email'].split('@')[1]
847+
if email_domain in self.bad_domains:
848+
raise forms.ValidationError(_("Registration using free " + \
849+
"email addresses is prohibited. Please supply a " + \
850+
"different email address."))
851+
return self.cleaned_data['email']
852+
853+
854+
~~class ResendActivationForm(forms.Form):
855+
~~ required_css_class = 'required'
856+
~~ email = forms.EmailField(label=_("E-mail"))
857+
```

0 commit comments

Comments
 (0)