Commit 9c4ea158cc4b36e567442b9e20108d241c16feb1
1 parent
294c5071
Exists in
master
and in
2 other branches
Modified news forms to include crop fields
Showing
1 changed file
with
41 additions
and
1 deletions
Show diff stats
news/forms.py
... | ... | @@ -3,10 +3,50 @@ from django.utils.translation import ugettext_lazy as _ |
3 | 3 | |
4 | 4 | from .models import News |
5 | 5 | from resubmit.widgets import ResubmitFileWidget |
6 | - | |
6 | +from os.path import join | |
7 | +from PIL import Image | |
8 | +import os | |
9 | +from amadeus import settings | |
7 | 10 | |
8 | 11 | class NewsForm(forms.ModelForm): |
9 | 12 | MAX_UPLOAD_SIZE = 5*1024*1024 |
13 | + | |
14 | + #Cropping image | |
15 | + x = forms.FloatField(widget=forms.HiddenInput(),required=False) | |
16 | + y = forms.FloatField(widget=forms.HiddenInput(),required=False) | |
17 | + width = forms.FloatField(widget=forms.HiddenInput(),required=False) | |
18 | + height = forms.FloatField(widget=forms.HiddenInput(),required=False) | |
19 | + | |
20 | + def save(self, commit=True): | |
21 | + super(NewsForm, self).save(commit=False) | |
22 | + self.deletepath = "" | |
23 | + | |
24 | + x = self.cleaned_data.get('x') | |
25 | + y = self.cleaned_data.get('y') | |
26 | + w = self.cleaned_data.get('width') | |
27 | + h = self.cleaned_data.get('height') | |
28 | + | |
29 | + if self.instance.image : | |
30 | + image = Image.open(self.instance.image) | |
31 | + if not x is None: | |
32 | + cropped_image = image.crop((x, y, w+x, h+y)) | |
33 | + resized_image = cropped_image.resize((700, 200), Image.ANTIALIAS) | |
34 | + | |
35 | + folder_path = join(settings.MEDIA_ROOT, 'news') | |
36 | + #check if the folder already exists | |
37 | + if not os.path.isdir(folder_path): | |
38 | + os.makedirs(folder_path) | |
39 | + | |
40 | + if ("news" not in self.instance.image.path): | |
41 | + self.deletepath = self.instance.image.path | |
42 | + | |
43 | + resized_image.save(self.instance.image.path) | |
44 | + | |
45 | + self.instance.save() | |
46 | + if (self.deletepath): | |
47 | + os.remove(self.deletepath) | |
48 | + return self.instance | |
49 | + | |
10 | 50 | class Meta: |
11 | 51 | model = News |
12 | 52 | fields = ['title','image','content'] | ... | ... |