0

when i am saving the modelform with blank image field, then it shows error, And this error is due to the custom form validation of image field in the modelform. And also the if statement is not working in custom form validation method.

" '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 Answer 1

1

The error is on the form

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

you should get the image like

if 'image' in request.FILES:
    image = request.FILES['image']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.