2012-04-26 03:44:16 +00:00
|
|
|
from django import forms
|
|
|
|
|
|
2012-09-28 04:42:13 +00:00
|
|
|
from taggit.forms import TagField
|
|
|
|
|
|
2012-04-26 03:44:16 +00:00
|
|
|
from .models import Pin
|
|
|
|
|
|
|
|
|
|
|
2013-02-23 20:33:10 +01:00
|
|
|
class PinForm(forms.Form):
|
2012-07-03 02:24:34 +00:00
|
|
|
url = forms.CharField(label='URL', required=False)
|
2012-07-24 21:23:27 +00:00
|
|
|
image = forms.ImageField(label='or Upload', required=False)
|
2013-02-23 20:33:10 +01:00
|
|
|
description = forms.CharField(label='Description', required=False, widget=forms.Textarea)
|
2012-09-28 04:42:13 +00:00
|
|
|
tags = TagField()
|
2012-07-24 21:23:27 +00:00
|
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
2013-02-23 20:33:10 +01:00
|
|
|
super(forms.Form, self).__init__(*args, **kwargs)
|
2012-05-01 04:42:45 +00:00
|
|
|
|
2012-07-03 02:24:34 +00:00
|
|
|
def check_if_image(self, data):
|
2012-05-01 04:42:45 +00:00
|
|
|
# Test file type
|
|
|
|
|
image_file_types = ['png', 'gif', 'jpeg', 'jpg']
|
|
|
|
|
file_type = data.split('.')[-1]
|
|
|
|
|
if file_type.lower() not in image_file_types:
|
2012-05-12 00:27:02 +00:00
|
|
|
raise forms.ValidationError("Requested URL is not an image file. "
|
|
|
|
|
"Only images are currently supported.")
|
2012-05-01 04:42:45 +00:00
|
|
|
|
2012-07-03 02:24:34 +00:00
|
|
|
def clean(self):
|
|
|
|
|
cleaned_data = super(PinForm, self).clean()
|
|
|
|
|
|
|
|
|
|
url = cleaned_data.get('url')
|
|
|
|
|
image = cleaned_data.get('image')
|
2012-05-01 04:42:45 +00:00
|
|
|
|
2012-07-03 02:24:34 +00:00
|
|
|
if url:
|
|
|
|
|
self.check_if_image(url)
|
2012-05-01 04:42:45 +00:00
|
|
|
try:
|
2012-07-03 02:24:34 +00:00
|
|
|
Pin.objects.get(url=url)
|
2012-05-01 04:42:45 +00:00
|
|
|
raise forms.ValidationError("URL has already been pinned!")
|
|
|
|
|
except Pin.DoesNotExist:
|
2012-07-03 02:24:34 +00:00
|
|
|
protocol = url.split(':')[0]
|
|
|
|
|
if protocol == 'http':
|
|
|
|
|
opp_url = url.replace('http://', 'https://')
|
|
|
|
|
elif protocol == 'https':
|
|
|
|
|
opp_url = url.replace('https://', 'http://')
|
|
|
|
|
else:
|
|
|
|
|
raise forms.ValidationError("Currently only support HTTP and "
|
|
|
|
|
"HTTPS protocols, please be sure "
|
|
|
|
|
"you include this in the URL.")
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
Pin.objects.get(url=opp_url)
|
|
|
|
|
raise forms.ValidationError("URL has already been pinned!")
|
|
|
|
|
except Pin.DoesNotExist:
|
|
|
|
|
pass
|
|
|
|
|
elif image:
|
|
|
|
|
pass
|
|
|
|
|
else:
|
|
|
|
|
raise forms.ValidationError("Need either a URL or Upload.")
|
|
|
|
|
|
|
|
|
|
return cleaned_data
|