如何将 FileField 的初始值传递给 Formset(在 Django 中) [英] how to pass initial value of FileField to Formset (in Django)

查看:17
本文介绍了如何将 FileField 的初始值传递给 Formset(在 Django 中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用来自 POST/FILE 请求的数据填充 Django 表单集.我能够填充除 FileField 之外的所有字段.似乎 initial 不能用于将 request.FILE 传递给 FormSet creator 函数.我的问题是如何将 FILE 传递给 FormSet.

I am trying to populate a Django formset using data from a POST/FILE request. I am able to populate all the fields except the FileField. It seems that initial cannot be used to pass the request.FILE to the FormSet creator function. My question is how to pass the FILE to FormSet.

模型.py

class ArticleForm(forms.Form):
     docfile = forms.FileField()
     subject = forms.Charfield(max_length=128)

ArticleFormSet = formset_factory(ArticleForm, extra=2)

views.py

formset = ArticleFormSet(request.POST, request.FILE)
#do some other work, and then re-display the POST data

data = formset.cleaned_data
formset = ArticleFormSet(initial=data)

return render_to_response('some.html',
                          {'formset':formset}
                         )

推荐答案

您不能将初始数据传递到文件字段.<input type="file"/> 在浏览器呈现时将始终为空白.

You can not pass initial data to a file field. The <input type="file" /> will always be blank when the browser renders it.

要将 request.FILES 传递给表单集,只需将其指定为 POST 后的第二个参数即可.

To pass request.FILES to a formset, just specify it as the second argument after POST.

http://docs.djangoproject.com/en/dev/topics/forms/formsets/#using-a-formset-in-views-and-templates

FormSet(request.POST, request.FILES)

这篇关于如何将 FileField 的初始值传递给 Formset(在 Django 中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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