Replicating an image in ImageField after checking for error in Django

My admin interface has a form with ImageField. Everything works fine, except when some other field causes a validation error. In these cases, the form is returned to the user for correction, but the already downloaded image file is cleared of the form.

Any idea on how to reload an already submitted image into a form in some way to allow the image to be saved?

Thanks!

Request interesting snippets of code:

class DealForm(forms.ModelForm): image = forms.ImageField(required=False,widget=AdminImageWidget) def clean(): data = self.cleaned_data date_start = data.get('date_start') date_end = data.get('date_end') (... several other validations ...) return data 

.

 class AdminImageWidget(forms.FileInput): def __init__(self, attrs={}): super(AdminImageWidget, self).__init__(attrs) def render(self, name, value, attrs=None): output = [] if value and hasattr(value, "url"): output.append(('<a target="_blank" href="%s">' '<img src="%s" /></a> ' % (value.url, value.url_200x150))) output.append(super(AdminImageWidget, self).render(name, value, attrs)) return mark_safe(u''.join(output)) 
+4
source share
2 answers

HTML <input type="file"> fields cannot be pre-populated with data. Therefore, if the check is not performed in another field, you will have to reselect the image.

This is an HTML / browser security measure. As anyway!

Imagine if a site can insert C:\Windows\something_important into a form in the corner of the page?


If this is critical functionality, you can ...

  • Force download the file before checking the form and enter the file name into the user session.
  • Customize your template to display a Success message when it displays again if the file is uploaded.
  • Disable file field validation when the session contains download information
  • Pull file name out of session after valid valid form submission
+6
source

Here is a django application called django-file-resubmit. This solves exactly this problem.

https://github.com/un1t/django-file-resubmit

+5
source

Source: https://habr.com/ru/post/1343570/


All Articles