forms.py
1.09 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
import base64
import StringIO
from django import forms
from django.utils.translation import ugettext_lazy as _
from PIL import Image
from .models import Badge
class BadgeForm(forms.ModelForm):
image = forms.ImageField(label=_(u'Image'), required=False)
class Meta:
model = Badge
fields = (
'title', 'description', 'image', 'user_attr', 'comparison',
'value', 'awardees'
)
def clean_image(self):
if not self.instance.pk and not self.cleaned_data['image']:
raise forms.ValidationError(_(u'You must add an Image'))
return self.cleaned_data['image']
def save(self, commit=True):
instance = super(BadgeForm, self).save(commit=False)
if self.cleaned_data['image']:
img = Image.open(self.cleaned_data['image'])
img = img.resize((50, 50), Image.ANTIALIAS)
f = StringIO.StringIO()
img.save(f, 'png')
instance.image_base64 = f.getvalue().encode('base64')
f.close()
if commit:
instance.save()
return instance