验证在ImageField上抛出错误

时间:2011-05-31 18:05:35

标签: django image-processing django-models django-forms

我有一个用户上传头像的表单,它会调整照片的大小并使用新的头像重新加载页面。表单工作完美,无需任何验证。

当我添加验证以在图像低于特定大小时引发错误时,forms.ValidationError正常工作。但是,当数据 通过验证时,会导致表单出错。

以下是我目前的情况 -

def handle_uploaded_image(i):
   ### enter size of thumbnail, returns (filename, content)        

def getting_started_pic(request):
    form = ProfilePictureForm()
    username = request.session.get('username')
    profile = UserProfile.objects.get(user=username) 
    if request.method == 'POST':
        form = ProfilePictureForm(request.POST, request.FILES)
        if form.is_valid():
            form = ProfilePictureForm(request.POST, request.FILES, instance = profile)
            ob = form.save(commit=False)
            try:
                t = handle_uploaded_image(request.FILES['avatar'])
                ob.avatar.save(t[0],t[1])
            except KeyError:
                ob.save()
            return render_to_response (...)
    return render_to_response (...)

在models.py -

class ProfilePictureForm(ModelForm):
    avatar = forms.ImageField()
    class Meta:
        model = UserProfile
        fields = ('avatar')

    def clean_avatar(self):
        import StringIO
        from PIL import Image, ImageOps        

        str=""
        for c in self.cleaned_data['avatar'].chunks():
            str += c

        imagefile = StringIO.StringIO(str)
        image = Image.open(imagefile)

        width, height = image.size[0], image.size[1]
        if width < 200 or height < 200:
            raise forms.ValidationError("Please upload an image at least 200 pixels wide.")
        else:
            return self.cleaned_data['avatar']

因此,当我使用此验证并返回cleaned_data时,它会抛出以下错误:

The UserProfile could not be changed because the data didn't validate.

从回溯中,抛出错误的行是:ob = form.save(commit=False),因此它看起来像是模型级验证错误。你能告诉我为什么会出现这个错误,以及我如何解决它?谢谢

1 个答案:

答案 0 :(得分:4)

可能是这样的:

form = ProfilePictureForm(request.POST, request.FILES)
if form.is_valid():
    form = ProfilePictureForm(request.POST, request.FILES, instance = profile)
    ...

表单验证后,使用从数据库中已有的实例创建的新ModelForm覆盖表单。这将删除您刚刚上传的内容的任何引用,因此它不会验证?

只需尝试:

form = ProfilePictureForm(request.POST, request.FILES, instance = profile)
if form.is_valid():
    ...