在 Django 中验证错误后在 ImageField 中重新提交图像 [英] Resubmitting Image in ImageField after Validation Error in Django

查看:19
本文介绍了在 Django 中验证错误后在 ImageField 中重新提交图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的管理界面中有一个带有 ImageField 的表单.除非其他一些字段引发验证错误,否则一切都很好.在这些情况下,表单会返回给用户进行更正,但已加载的图像文件将从表单中清除.

I have, in my admin interface, a form with a ImageField. Everything works great except when some other field raises a validation error. In those cases, the form returns to the user for correction, but the already loaded image file is cleared from the form.

知道如何以某种方式将已经提交的图像重新加载到表单中以允许保存图像吗?

Any idea in how to, somehow, reload the already submitted image to the form in order to allow the image beeing saved?

谢谢!

一些有趣的代码:

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))

推荐答案

HTML 字段不能预先填充数据.因此,如果另一个字段的验证失败,您将不得不重新选择图像.

HTML <input type="file"> fields cannot be prepopulated with data. Therefore, if validation fails on another field, you will have to re-select the image.

这是一种 HTML/浏览器安全措施.就像,没有办法绕过它!

It's a HTML / browser security measure. As in, no way around it!

想象一下,一个站点是否可以将 C:Windowssomething_important 注入页面角落的表单中?

Imagine if a site could inject C:Windowssomething_important into a form in the corner of the page?

如果这是关键功能,您可以...

If this is critical functionality, you could...

  1. 在表单验证之前强制上传文件并将文件名存储在用户会话中
  2. 设置您的模板以在上传文件时重新显示成功"消息
  3. 当会话包含上传信息时禁用文件字段验证
  4. 在真正有效的表单提交时从会话中提取文件名

这篇关于在 Django 中验证错误后在 ImageField 中重新提交图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆