我的forms.py文件中不断出现语法无效错误

时间:2016-09-11 18:36:46

标签: django python-3.x syntax-error modelform

当我运行服务器时,我收到syntaxerror消息(语法无效),指示行如果提交:是错误的。

这是我的forms.py文件:

from urllib import request
from django.core.files.base import ContentFile
from django.utils.text import slugify
from django import forms
from .models import Photo

from PIL import Image
from django.utils.translation import ugettext as _


class PhotoCreateForm(forms.ModelForm):

class Meta:
    model = Photo
    # fields = '__all__'
    fields = ('title', 'description', 'photo', 'license', 'location',  'url', 'slug')

    #hide url input from users with the HiddenInput widget
    widgets = {
        'url': forms.HiddenInput,
    }


def clean_title(self):
    title = self.cleaned_data.get("title")
    if len(title) > 3:
        return title
    else:
        raise forms.ValidationError("Title must be greater than 3 characters long.")


def clean_photo(self):
    photo = self.cleaned_data.get('photo', False)

    if photo:
        pho = Photo.open(photo)
        w, h = pho.size

        #validate dimensions
        max_width = max_height = 500
        if w > max_width or h > max_height:
            raise forms.ValidationError(
                _('Please use an image that is smaller or equal to '
                  '%s x %s pixels.' % (max_width, max_height)))

        #validate content type
        main, sub = photo.content_type.split('/')
        if not (main == 'photo' and sub.lower() in ['jpeg', 'pjpeg', 'png', 'jpg']):
            raise forms.ValidationError(_('Please upload a JPEG or PNG image.'))

        #validate file size
        if len(photo) > (1 * 1024 * 1024):
            raise forms.ValidationError(_('Image file too large ( maximum 1mb )'))
    else:
        raise forms.ValidationError(_("Couldn't read uploaded image"))
    return photo


def save(self, force_insert=False, force_update=False, commit=True):
    photo = super(PhotoCreateForm, self).save(commit=False)

    # generate photo name by combining photo title slug with file extension 
    photo_name = '{}.{}'.format(slugify(photo.title.lower()),


    photo.photo.save(photo_name,
                     ContentFile(response.read()),
                     save=False)

    if commit:
        photo.save()
    return photo

该错误表明lin if commit:是无效的语法。

我已检查过文档,但未将此行视为无效语法。

0 个答案:

没有答案