gpt4 book ai didi

Django 的 ClearableFileInput 小部件在提交时未传递初始 ("Currently") 值

转载 作者:行者123 更新时间:2023-12-05 08:01:45 24 4
gpt4 key购买 nike

我的基本目标是创建一个表单(使用 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 上,文件字段在新对象中最终变为空白。

所以:

  1. ClearableFileInput 小部件是否传递“当前”值?如果不是,ClearableFileInput 小部件是否具有误导性和/或用途非常有限?我假设返回的值将是“当前...”中的值,除非我使用“更改...”输入。

  2. 我如何捕获该值,以便在我调用 .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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com