class ProfileForm forms ModelForm first_name forms CharField required

 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
class ProfileForm(forms.ModelForm):
first_name = forms.CharField(required=False, max_length=30, label=u"Имя")
last_name = forms.CharField(required=False, max_length=30, label=u"Фамилия")
def __init__(self, *args, **kwargs):
super(ProfileForm, self).__init__(*args, **kwargs)
self.fields.keyOrder = ('first_name', 'last_name', 'location', 'sex', 'avatar')
class Meta:
model = UserProfile
fields = ('first_name', 'last_name', 'location', 'sex', 'avatar')
def clean_avatar(self):
if self.cleaned_data.get('avatar'):
if self.cleaned_data['avatar'].size > settings.MAX_AVATAR_FILE_SIZE * 1024:
raise forms.ValidationError(u"Превышен максимальный размер аватары")
return self.cleaned_data['avatar']
def save(self, request):
usr = request.user
# Modify user
usr.first_name = self.cleaned_data['first_name']
usr.last_name = self.cleaned_data['last_name']
usr.save()
#forms.save_instance(self, UserProfile(user=usr))
self.cleaned_data['user'] = usr
if self.cleaned_data.get('avatar'):
avatar = Image.open(StringIO(self.cleaned_data['avatar'].read()))
avatar.thumbnail(settings.AVATAR_SIZE, Image.ANTIALIAS)
output_avatar = StringIO()
avatar.save(output_avatar, avatar.format)
name = self.cleaned_data['avatar'].name
content_type = self.cleaned_data['avatar'].content_type
charset = self.cleaned_data['avatar'].charset
field_name = self.cleaned_data['avatar'].field_name
size = len(output_avatar.getvalue())
self.cleaned_data['avatar'] = InMemoryUploadedFile(output_avatar, field_name, name, content_type, size, charset)
return super(ProfileForm, self).save()