forms.py
2.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# coding=utf-8
from django import forms
from django.utils.translation import ugettext_lazy as _
from rolepermissions.shortcuts import assign_role
from .models import User
class Validation(forms.ModelForm):
MIN_PASS_LENGTH = 8
MAX_UPLOAD_SIZE = 2*1024*1024
def clean_image(self):
image = self.cleaned_data.get('image', False)
if image:
if image._size > self.MAX_UPLOAD_SIZE:
raise forms.ValidationError(_("The image is too large. It should have less than 2MB."))
return image
def clean_password(self):
password = self.cleaned_data.get('password')
if self.is_edit and len(password) == 0:
return password
# At least MIN_LENGTH long
if len(password) < self.MIN_PASS_LENGTH:
raise forms.ValidationError(_("The password must contain at least % d characters." % self.MIN_PASS_LENGTH))
# At least one letter and one non-letter
first_isalpha = password[0].isalpha()
if all(c.isalpha() == first_isalpha for c in password):
raise forms.ValidationError(_('The password must contain at least one letter and at least one digit or a punctuation character.'))
return password
def clean_password2(self):
password = self.cleaned_data.get("password")
password2 = self.cleaned_data.get("password2")
if self.is_edit and len(password) == 0:
return password2
if password and password2 and password != password2:
raise forms.ValidationError(_('The confirmation password is incorrect.'))
return password2
class RegisterUserForm(Validation):
password = forms.CharField(label=_('Password'), widget = forms.PasswordInput)
password2 = forms.CharField(label = _('Confirm Password'), widget = forms.PasswordInput)
is_edit = False
def save(self, commit=True):
super(RegisterUserForm, self).save(commit=False)
self.instance.set_password(self.cleaned_data['password'])
self.instance.save()
return self.instance
class Meta:
model = User
fields = ['email', 'username', 'last_name', 'social_name', 'image', 'show_email', ]
class ProfileForm(Validation):
password = forms.CharField(label=_('Password'), widget = forms.PasswordInput, required = False)
password2 = forms.CharField(label = _('Confirm Password'), widget = forms.PasswordInput, required = False)
is_edit = True
def save(self, commit=True):
super(ProfileForm, self).save(commit=False)
if len(self.cleaned_data['password']) > 0:
self.instance.set_password(self.cleaned_data['password'])
self.instance.save()
return self.instance
class Meta:
model = User
fields = ['social_name', 'description', 'show_email', 'image']
widgets = {
'description': forms.Textarea,
}