在Django中验证错误后,在ImageField中重新提交图像 [英] Resubmitting Image in ImageField after Validation Error in Django
问题描述
任何想法,无论如何,重新加载已经提交图像到表单,以便保存图像beeing?
谢谢!
SOme有趣的位的代码:
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')
(...几个其他验证...)
返回数据
。
class AdminImageWidget(forms.FileInput):
def __init __(self,attrs = {}):
super(AdminImageWidget,self).__ init __(attrs)
def render(self,name,value,attrs = None):
output = []
如果value和hasattr (value,url):
output.append(('< a target =_ blankhref =%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 < input type =file>
字段不能用数据预填充。因此,如果在另一个字段上验证失败,则必须重新选择该图像。
这是一个HTML /浏览器安全措施。像在,没有办法绕过它!
想像一下,如果一个网站可以将 C:\Windows\something_important
注入到页?
如果这是关键功能,可以...
- 在表单验证之前强制上传文件,并在用户会话中存放文件名。
- 设置您的模板以显示成功消息如果上传文件,请重新显示
- 在会话包含上传信息时禁用文件字段验证
- 在真实有效的表单提交时从您的会话中拉取文件名
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?
Thanks!
SOme interesting bits 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))
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.
It's a HTML / browser security measure. As in, no way around it!
Imagine if a site could inject C:\Windows\something_important
into a form in the corner of the page?
If this is critical functionality, you could...
- Force the file to be uploaded before form validation and stash the file name in the user session
- Set up your template to display a "success" message on re-display if file is uploaded
- Disable file field validation when session contains upload info
- Pull the filename from your session upon true valid form submission
这篇关于在Django中验证错误后,在ImageField中重新提交图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!