开发者

Validation throwing an error on ImageField

I have a form where a user uploads an avatar, and it resizes the photo and reloads the page with the new avatar. The form is working perfectly without any validation.

When I add a validation to raise an error if the image is below a certain size, the forms.ValidationError works fine. However, when the data does pass validation, it causes the form to error.

Here is what I currently have --

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 (...)

And in 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']

So when I use this validation 开发者_Python百科and it returns cleaned_data, it throws the following error:

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

From the traceback, the line throwing the error is: ob = form.save(commit=False), so it seems like a model-level validation error. Could you please tell me why this error is occurring, and how I can fix it? Thank you


Might it be this:

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

Once your form validates, you overwrite the form with a new ModelForm that is created from the instance already in the database. This will get rid of any reference to what you have just uploaded, so it won't validate?

Try it with just:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜