在用户注册时提示密码过短的功能的实现(alpha版时未解决的问题)
曹竹:代码片段如下,应该很容易看懂,不解释了
if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
password1=self.cleaned_data['password1']
if password1!= self.cleaned_data['password2']:
raise forms.ValidationError(_(u'You must type the same password each time'))
if len(password1)<=5 :
raise forms.ValidationError(_(u'length of your password must be at least 6'))
return self.cleaned_data
代码是在文件mysite/registration/forms.py中
顺便贴下forms.py的完整源码:
1 """
2 Forms and validation code for user registration.
3
4 """
5
6
7 from django import forms
8 from django.utils.translation import ugettext_lazy as _
9 from django.contrib.auth.models import User
10
11 from registration.models import RegistrationProfile
12
13
14 # I put this on all required fields, because it's easier to pick up
15 # on them with CSS or JavaScript if they have a class of "required"
16 # in the HTML. Your mileage may vary. If/when Django ticket #3515
17 # lands in trunk, this will no longer be necessary.
18 attrs_dict = { 'class': 'required' }
19
20
21 class RegistrationForm(forms.Form):
22 """
23 Form for registering a new user account.
24
25 Validates that the requested username is not already in use, and
26 requires the password to be entered twice to catch typos.
27
28 Subclasses should feel free to add any additional validation they
29 need, but should either preserve the base ``save()`` or implement
30 a ``save()`` which accepts the ``profile_callback`` keyword
31 argument and passes it through to
32 ``RegistrationProfile.objects.create_inactive_user()``.
33
34 """
35 username = forms.RegexField(regex=r'^\w+$',
36 max_length=30,
37 widget=forms.TextInput(attrs=attrs_dict),
38 label=_(u'username'))
39 email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict,
40 maxlength=75)),
41 label=_(u'email address'))
42 password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False),
43 label=_(u'password'))
44 password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False),
45 label=_(u'password (again)'))
46
47 def clean_username(self):
48 """
49 Validate that the username is alphanumeric and is not already
50 in use.
51
52 """
53 try:
54 user = User.objects.get(username__iexact=self.cleaned_data['username'])
55 except User.DoesNotExist:
56 return self.cleaned_data['username']
57 raise forms.ValidationError(_(u'This username is already taken. Please choose another.'))
58
59 def clean(self):
60 """
61 Verifiy that the values entered into the two password fields
62 match. Note that an error here will end up in
63 ``non_field_errors()`` because it doesn't apply to a single
64 field.
65
66 """
67 if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
68 password1=self.cleaned_data['password1']
69 if password1!= self.cleaned_data['password2']:
70 raise forms.ValidationError(_(u'You must type the same password each time'))
71 if len(password1)<=5 :
72 raise forms.ValidationError(_(u'length of your password must be at least 6'))
73 return self.cleaned_data
74
75
76 def save(self, profile_callback=None):
77 """
78 Create the new ``User`` and ``RegistrationProfile``, and
79 returns the ``User``.
80
81 This is essentially a light wrapper around
82 ``RegistrationProfile.objects.create_inactive_user()``,
83 feeding it the form data and a profile callback (see the
84 documentation on ``create_inactive_user()`` for details) if
85 supplied.
86
87 """
88 new_user = RegistrationProfile.objects.create_inactive_user(username=self.cleaned_data['username'],
89 password=self.cleaned_data['password1'],
90 email=self.cleaned_data['email'],
91 profile_callback=profile_callback)
92 return new_user
93
94
95 class RegistrationFormTermsOfService(RegistrationForm):
96 """
97 Subclass of ``RegistrationForm`` which adds a required checkbox
98 for agreeing to a site's Terms of Service.
99
100 """
101 tos = forms.BooleanField(widget=forms.CheckboxInput(attrs=attrs_dict),
102 label=_(u'I have read and agree to the Terms of Service'),
103 error_messages={ 'required': u"You must agree to the terms to register" })
104
105
106 class RegistrationFormUniqueEmail(RegistrationForm):
107 """
108 Subclass of ``RegistrationForm`` which enforces uniqueness of
109 email addresses.
110
111 """
112 def clean_email(self):
113 """
114 Validate that the supplied email address is unique for the
115 site.
116
117 """
118 if User.objects.filter(email__iexact=self.cleaned_data['email']):
119 raise forms.ValidationError(_(u'This email address is already in use. Please supply a different email address.'))
120 return self.cleaned_data['email']
121
122
123 class RegistrationFormNoFreeEmail(RegistrationForm):
124 """
125 Subclass of ``RegistrationForm`` which disallows registration with
126 email addresses from popular free webmail services; moderately
127 useful for preventing automated spam registrations.
128
129 To change the list of banned domains, subclass this form and
130 override the attribute ``bad_domains``.
131
132 """
133 bad_domains = ['aim.com', 'aol.com', 'email.com', 'gmail.com',
134 'googlemail.com', 'hotmail.com', 'hushmail.com',
135 'msn.com', 'mail.ru', 'mailinator.com', 'live.com']
136
137 def clean_email(self):
138 """
139 Check the supplied email address against a list of known free
140 webmail domains.
141
142 """
143 email_domain = self.cleaned_data['email'].split('@')[1]
144 if email_domain in self.bad_domains:
145 raise forms.ValidationError(_(u'Registration using free email addresses is prohibited. Please supply a different email address.'))
146 return self.cleaned_data['email']
posted on 2011-05-29 00:05 banana.totolv 阅读(351) 评论(0) 编辑 收藏 举报