[Django]-How to prefill the image field on form validation error Django?

3👍

Validate the form on the client side using JavaScript, and prevent submission unless the form is valid. That way, you won’t lose the existing content because your form won’t get submitted unless it’s already validated OK.

Assuming you’re using jQuery, you could bind to the click event of the submit button, and use preventDefault to stop the default behaviour. Then validate the form, and submit it only if it appears to be valid.

That way you will only ever have the form submitted to Django once it has already been validated and so as long as your client-side validation is reliable, you shouldn’t experience this issue.

2👍

To show the image in the view, it would need to be saved to your server, S3, or whatever else you are using for static/media files.

From JavaScript, you may be able to store the chosen file in localStorage, and set the remembered chosen path on form error. I’m not sure if the HTML5 filesystem API allows this. See http://www.html5rocks.com/en/tutorials/file/filesystem/

As Matthew Daly said, going with client-side validation is the best choice; anything else would probably be a headache.

👤kevins

Leave a comment