From 4b2fc752868aab035fbcf62d2cde8552df036893 Mon Sep 17 00:00:00 2001 From: Krzysztof Klimonda Date: Sun, 24 Feb 2013 17:20:20 +0100 Subject: [PATCH] Simplify the PinForm.clean method I have a gut feeling that we could refactor some code out of this method, but for now I'll just clean it up a bit. --- pinry/pins/forms.py | 43 +++++++++++++++++-------------------------- 1 file changed, 17 insertions(+), 26 deletions(-) diff --git a/pinry/pins/forms.py b/pinry/pins/forms.py index 3589832..be55071 100644 --- a/pinry/pins/forms.py +++ b/pinry/pins/forms.py @@ -4,20 +4,12 @@ from .models import Pin class PinForm(forms.ModelForm): - url = forms.CharField(label='url', required=False) + url = forms.CharField(required=False) image = forms.ImageField(label='or Upload', required=False) class Meta: model = Pin - fields = ['url', 'description', 'tags'] - - def check_if_image(self, data): - # Test file type - image_file_types = ['png', 'gif', 'jpeg', 'jpg'] - file_type = data.split('.')[-1] - if file_type.lower() not in image_file_types: - raise forms.ValidationError("Requested URL is not an image file. " - "Only images are currently supported.") + fields = ['url', 'image', 'description', 'tags'] def clean(self): cleaned_data = super(PinForm, self).clean() @@ -26,26 +18,25 @@ class PinForm(forms.ModelForm): image = cleaned_data.get('image') if url: - self.check_if_image(url) + image_file_types = ['png', 'gif', 'jpeg', 'jpg'] + if not url.split('.')[-1].lower() in image_file_types: + raise forms.ValidationError("Requested URL is not an image file. " + "Only images are currently supported.") + try: + Pin.objects.get(url=url) + raise forms.ValidationError("URL has already been pinned!") + except Pin.DoesNotExist: + pass + protocol = url.split(':')[0] + if protocol not in ['http', 'https']: + raise forms.ValidationError("Currently only support HTTP and " + "HTTPS protocols, please be sure " + "you include this in the URL.") try: Pin.objects.get(url=url) raise forms.ValidationError("URL has already been pinned!") except Pin.DoesNotExist: - 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 + pass elif image: pass else: