0

Is it possible, when calling ImageModel.save(), to check if an image file has been uploaded?

For example:

  • When creating the object, an image file should be uploaded in 99% of cases. If an image file is not uploaded, we may give an error or allow the user to create a placeholder object.
  • When updating the object, the user may upload a new image file to replace it, or the user may upload no image file and only change a CharField in the object (and the previous image file remains).

save() will be overridden to resize the uploaded image file using Pillow, compressed and optimized using mozjpeg, and finally saved to S3.

How can I check if an image file is being uploaded so that the Update cases can be accomodated?

davidtgq
  • 3,780
  • 10
  • 43
  • 80
  • You can check the image field in the form rather than in the back-end code and validate whether the image field has value or not. – Raj Subit Mar 21 '16 at 11:03

1 Answers1

0

You can check the image field in the form rather than in the back-end code and validate whether the image field has value or not.

For eg: If you field name is image then you can do:

In forms.py

image = forms.Imagefield(required=True)
Raj Subit
  • 1,487
  • 2
  • 12
  • 23
  • Would this cause a validation error if no image file is uploaded when updating the object? – davidtgq Mar 21 '16 at 11:14
  • This will basically check for whether the field has input or not and raise "field is required" if no file is uploaded – Raj Subit Mar 21 '16 at 11:17
  • So if the user is updating the object without uploading a new image file, I would have to catch the exception and provide the logic for updating the description etc. in the exception? – davidtgq Mar 21 '16 at 11:20
  • You need not do anything. If user tries to update without uploading image file then an alert will be shown stating the field is required and the form will not be saved until file is uploaded – Raj Subit Mar 21 '16 at 11:21
  • What if the user wants to update a CharField in the object without changing the ImageField? Does he have to re-upload his image every time? – davidtgq Mar 21 '16 at 11:25
  • No user does not have to re-upload image to change other fields. If the user leaves the image field empty and pressed the save button, then an alert is shown to upload a file in the image field. However, if there is a file present in the image field then user can save the form easily. Other fields are not hampered by the code – Raj Subit Mar 21 '16 at 11:28