1 from django import forms
3 from django.utils.translation import ugettext as _
4 from django.utils.safestring import mark_safe
5 from forum import settings
6 from django.http import str_to_unicode
7 from forum.models import User
8 from forum.modules import call_all_handlers
12 DEFAULT_NEXT = getattr(settings, 'APP_BASE_URL')
16 next = str_to_unicode(urllib.unquote(next), 'utf-8')
18 if next.startswith('/'):
22 def get_next_url(request):
23 return clean_next(request.REQUEST.get('next'))
25 class StrippedNonEmptyCharField(forms.CharField):
26 def clean(self,value):
28 if self.required and value == '':
29 raise forms.ValidationError(_('this field is required'))
32 class NextUrlField(forms.CharField):
34 super(NextUrlField,self).__init__(max_length = 255,widget = forms.HiddenInput(),required = False)
35 def clean(self,value):
36 return clean_next(value)
38 login_form_widget_attrs = { 'class': 'required login' }
39 username_re = re.compile(r'^[\-\w\s ]+$', re.UNICODE)
41 class UserNameField(StrippedNonEmptyCharField):
42 def __init__(self,db_model=User, db_field='username', must_exist=False,skip_clean=False,label=_('choose a username'),**kw):
43 self.must_exist = must_exist
44 self.skip_clean = skip_clean
45 self.db_model = db_model
46 self.db_field = db_field
47 error_messages={'required':_('user name is required'),
48 'taken':_('sorry, this name is taken, please choose another'),
49 'forbidden':_('sorry, this name is not allowed, please choose another'),
50 'missing':_('sorry, there is no user with this name'),
51 'multiple-taken':_('sorry, we have a serious error - user name is taken by several users'),
52 'invalid':_('user name can only consist of letters, empty space, hyphens and underscore'),
53 'toshort':_('user name is to short, please use at least %d characters') % settings.MIN_USERNAME_LENGTH
55 if 'error_messages' in kw:
56 error_messages.update(kw['error_messages'])
57 del kw['error_messages']
58 super(UserNameField,self).__init__(max_length=30,
59 widget=forms.TextInput(attrs=login_form_widget_attrs),
61 error_messages=error_messages,
65 def clean(self,username):
66 """ validate username """
67 if self.skip_clean == True:
69 if hasattr(self, 'user_instance') and isinstance(self.user_instance, User):
70 if username == self.user_instance.username:
73 username = super(UserNameField, self).clean(username)
74 except forms.ValidationError:
75 raise forms.ValidationError(self.error_messages['required'])
76 if len(username) < settings.MIN_USERNAME_LENGTH:
77 raise forms.ValidationError(self.error_messages['toshort'])
78 if self.required and not username_re.match(username):
79 raise forms.ValidationError(self.error_messages['invalid'])
80 if username in settings.RESERVED_USERNAMES:
81 raise forms.ValidationError(self.error_messages['forbidden'])
83 user = self.db_model.objects.get(
84 **{'%s' % self.db_field : username}
90 raise forms.ValidationError(self.error_messages['taken'])
91 except self.db_model.DoesNotExist:
93 raise forms.ValidationError(self.error_messages['missing'])
96 except self.db_model.MultipleObjectsReturned:
97 raise forms.ValidationError(self.error_messages['multiple-taken'])
99 class UserEmailField(forms.EmailField):
100 def __init__(self,skip_clean=False,**kw):
101 self.skip_clean = skip_clean
102 super(UserEmailField,self).__init__(widget=forms.TextInput(attrs=dict(login_form_widget_attrs,
103 maxlength=200)), label=mark_safe(_('your email address')),
104 error_messages={'required':_('email address is required'),
105 'invalid':_('please enter a valid email address'),
106 'taken':_('this email is already used by someone else, please choose another'),
111 def clean(self,email):
112 """ validate if email exist in database
114 return: raise error if it exist """
115 email = super(UserEmailField,self).clean(email.strip())
118 if settings.EMAIL_UNIQUE == True:
120 user = User.objects.get(email = email)
121 raise forms.ValidationError(self.error_messages['taken'])
122 except User.DoesNotExist:
124 except User.MultipleObjectsReturned:
125 raise forms.ValidationError(self.error_messages['taken'])
129 class UserRealNameField(StrippedNonEmptyCharField):
130 def __init__(self, db_model=User, db_field='real_name', must_exist=True, skip_clean=False, label=_('Your real name'),**kw):
131 self.must_exist = must_exist
132 self.skip_clean = skip_clean
133 self.db_model = db_model
134 self.db_field = db_field
135 error_messages={'required':_('Real name is required')
137 if 'error_messages' in kw:
138 error_messages.update(kw['error_messages'])
139 del kw['error_messages']
140 super(UserRealNameField,self).__init__(max_length=100,
141 widget=forms.TextInput(attrs=login_form_widget_attrs),
143 error_messages=error_messages,
147 def clean(self, real_name):
148 if self.skip_clean == True:
151 return super(UserRealNameField, self).clean(real_name)
152 except forms.ValidationError:
153 raise forms.ValidationError(self.error_messages['required'])
155 class SetPasswordForm(forms.Form):
156 password1 = forms.CharField(widget=forms.PasswordInput(attrs=login_form_widget_attrs),
157 label=_('choose password'),
158 error_messages={'required':_('password is required')},
160 password2 = forms.CharField(widget=forms.PasswordInput(attrs=login_form_widget_attrs),
161 label=mark_safe(_('retype password')),
162 error_messages={'required':_('please, retype your password'),
163 'nomatch':_('sorry, entered passwords did not match, please try again')},
166 def __init__(self, data=None, user=None, *args, **kwargs):
167 super(SetPasswordForm, self).__init__(data, *args, **kwargs)
169 def clean_password2(self):
171 Validates that the two password inputs match.
174 if 'password1' in self.cleaned_data:
175 if self.cleaned_data['password1'] == self.cleaned_data['password2']:
176 self.password = self.cleaned_data['password2']
177 self.cleaned_data['password'] = self.cleaned_data['password2']
178 return self.cleaned_data['password2']
180 del self.cleaned_data['password2']
181 raise forms.ValidationError(self.fields['password2'].error_messages['nomatch'])
183 return self.cleaned_data['password2']
185 class SimpleCaptchaForm(forms.Form):
188 def __init__(self, *args, **kwargs):
189 super(SimpleCaptchaForm, self).__init__(*args, **kwargs)
191 spam_fields = call_all_handlers('create_anti_spam_field')
193 spam_fields = dict(spam_fields)
194 for name, field in spam_fields.items():
195 self.fields[name] = field
197 self._anti_spam_fields = spam_fields.keys()
199 self._anti_spam_fields = []