bgneal@695
|
1 """Forms for the user_photos application."""
|
bgneal@700
|
2 import datetime
|
bgneal@700
|
3
|
bgneal@695
|
4 from django import forms
|
bgneal@697
|
5 from django.conf import settings
|
bgneal@695
|
6
|
bgneal@700
|
7 from core.s3 import S3Bucket
|
bgneal@700
|
8 from core.image_uploader import upload
|
bgneal@696
|
9 from user_photos.models import Photo
|
bgneal@696
|
10
|
bgneal@695
|
11
|
bgneal@695
|
12 class UploadForm(forms.Form):
|
bgneal@695
|
13 image_file = forms.ImageField()
|
bgneal@696
|
14
|
bgneal@696
|
15 def __init__(self, *args, **kwargs):
|
bgneal@696
|
16 self.user = kwargs.pop('user')
|
bgneal@696
|
17 super(UploadForm, self).__init__(*args, **kwargs)
|
bgneal@696
|
18
|
bgneal@696
|
19 def save(self):
|
bgneal@696
|
20 """Processes the image and creates a new Photo object, which is saved to
|
bgneal@696
|
21 the database. The new Photo instance is returned.
|
bgneal@696
|
22
|
bgneal@696
|
23 This function should only be called if is_valid() returns True.
|
bgneal@696
|
24
|
bgneal@696
|
25 """
|
bgneal@700
|
26 bucket = S3Bucket(access_key=settings.USER_PHOTOS_ACCESS_KEY,
|
bgneal@700
|
27 secret_key=settings.USER_PHOTOS_SECRET_KEY,
|
bgneal@700
|
28 base_url=settings.USER_PHOTOS_BASE_URL,
|
bgneal@700
|
29 bucket_name=settings.USER_PHOTOS_BUCKET)
|
bgneal@700
|
30
|
bgneal@700
|
31 now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
bgneal@700
|
32 metadata = {'user': self.user.username, 'date': now}
|
bgneal@700
|
33
|
bgneal@700
|
34 url, thumb_url = upload(fp=self.cleaned_data['image_file'],
|
bgneal@700
|
35 bucket=bucket,
|
bgneal@700
|
36 metadata=metadata,
|
bgneal@700
|
37 new_size=settings.USER_PHOTOS_MAX_SIZE,
|
bgneal@700
|
38 thumb_size=settings.USER_PHOTOS_THUMB_SIZE)
|
bgneal@700
|
39
|
bgneal@696
|
40 photo = Photo(user=self.user, url=url, thumb_url=thumb_url)
|
bgneal@696
|
41 photo.save()
|
bgneal@696
|
42 return photo
|