- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我的基本目标是创建一个表单(使用 ModelForm
),预填充现有数据库对象中的数据,允许用户修改这些数据,然后将提交的表单另存为新对象. (有点像“复制”然后“粘贴修改”设置。)除了文件字段和 ClearableFileInput 小部件外,这工作正常。
this 等问题的答案, this , 和 this明确文件字段不能也不应该填充初始值。
然而,Django 文档在 ClearableFileInput 上小部件说:
File upload input:
<input type='file' ...>
, with an additional checkbox input to clear the field's value, if the field is not required and has initial data.
(已经有点困惑了,但我假设 Django 指的是具有初始值的 model 字段,而 <input type='file' ...>
字段仍然是空白?)
因此,如果我使用以下任一方法:
>>> obj = Foo.objects.get(pk=1)
>>> obj.fooFile.name
u'files/foo1.txt'
>>> f = FooForm(instance=obj)
或者这个方法:
f = FooForm(initial={'fooFile':Foo.objects.get(pk=1).fooFile})
为了实例化我的表单,ClearableFileInput 小部件显示:
Currently with clearing checkbox, Change... input http://phagesdb.org/static/formDisplay.png
然而,当用户在不更改此字段的情况下提交表单时,“当前”行的值似乎完全丢失给 Django。它似乎不在 request.POST
中。或 form.cleaned_data
.当我调用 .is_valid()
然后 .save()
在我绑定(bind)的 ModelForm 上,文件字段在新对象中最终变为空白。
所以:
ClearableFileInput 小部件是否传递“当前”值?如果不是,ClearableFileInput 小部件是否具有误导性和/或用途非常有限?我假设返回的值将是“当前...”中的值,除非我使用“更改...”输入。
我如何捕获该值,以便在我调用 .save()
时它出现在我的新对象中? (请记住,我不能使用 f = FooForm(request.POST, request.FILES, instance=obj)
,因为我想要一个新对象,而不是修改后的对象。)
最佳答案
在您的表单中放置一个隐藏字段,并使用您作为初始传入的图像的路径预填充它。然后写一个类似下面的保存方法。
这对用户来说就像预填充文件字段一样,将文件保存到新实例,并允许他们使用清除复选框,或上传他们自己的图像。
from django.core.files.base import ContentFile
def save(self, commit=True):
insance = super(FormClass, self).save(False)
if not instance.file_field and self.cleaned_data['file_field_path'] and not self.data.get('file_field-clear'):
path = os.path.join(settings.MEDIA_ROOT, self.cleaned_data['file_field_path'])
with open(path) as f:
file_object = ContentFile(f.read())
instance.file_field.save(self.cleaned_data['file_field_path'], file_object, False)
if commit:
insance.save()
return insance
关于Django 的 ClearableFileInput 小部件在提交时未传递初始 ("Currently") 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12479856/
在我们的数据库表上,我们使用两个唯一的非聚集索引来创建跨四个字段的唯一约束。我们使用两个,因为其中一个字段 ZipCode 是一个可为空的字段。如果表中存在一条包含 ZipCode 的 null 条目
我刚刚开始学习 Rails 3 教程,以便对框架有一点熟悉,但我在生成 schema.rb 时遇到了问题。我的操作系统是 Windows 7 x64、Ruby 1.9.2、MySQL2 gem 0.2
我是一名优秀的程序员,十分优秀!