django自定义表单验证错误

时间:2015-03-25 07:24:33

标签: django django-models django-forms django-templates django-views

当我使用空白图像字段保存​​模型时,它显示错误,并且此错误是由于模型中图像字段的自定义表单验证。并且if语句在自定义表单验证方法中也不起作用。

" 'unicode' object has no attribute '_size' ".

models.py

class ImageUpload(models.Model):
    image  = models.ImageField(upload_to='uploads')
    name = models.CharField(max_length='128')

    class Meta:
        db_table = 'image_upload'

formy.py

 class ImageUploadForm(forms.ModelForm):

    class Meta:
     model = ImageUpload

    def clean_image(self):
       image = self.cleaned_data.get('image',None)
       if image: # this is not working, if image field is blank
          if image._size:
                if image:
                    if image._size > 1*1024*1024:
                        raise ValidationError("Image file too large ( > 4mb )")
                    return image
                else:
                    raise ValidationError("Couldn't read uploaded image")
            else:
                raise ValidationError("image format should be .png %s"%(image_format))

views.py

def add_image(request):
    response_data = {}

    if request.method == 'POST':
        form = ImageUploadForm(request.POST,request.FILES)
        context = {
                'form':form
                   }
        if form.is_valid():
            form.save()
            response_data['status'] = 'true'
            response_data['message'] = 'successfully added'
            return HttpResponse(json.dumps(response_data),content_type='application/javascript')
        else:
            response_data['message'] = form.errors
        #return HttpResponse(response_data)
        return HttpResponse(json.dumps(response_data),content_type='application/javascript')
    else:
        form = ImageUploadForm()
        context = {
                'form':form
                   }
        return render(request,'users/add_image.html',context)

1 个答案:

答案 0 :(得分:1)

错误在表格

image = self.cleaned_data.get('image',None)

你应该得到像

这样的图像
if 'image' in request.FILES:
    image = request.FILES['image']