0
當我保存模型與空白圖像字段,然後它顯示錯誤,這個錯誤是由於模型中的圖像字段的自定義表單驗證。而且if語句在自定義表單驗證方法中不起作用。django自定義表單驗證錯誤
" '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)
非常感謝@brunofitas圖像 – Thameem 2015-03-25 08:11:39