将初始化传递给Django的ModelFormSet [英] Passing initial into Django's ModelFormSet

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

问题描述

我有一个模型表单,我需要将关键字初始化传递给(在表单集中有一些初始值,例如日期设置为今天)。据我所知,查询参数(默认为YourModel.objects.all())将覆盖此初始空表单的创建能力。我将查询器指定为:YourModel.objects.none(),它阻止它使用数据库中的条目填写表单集,但是我仍然无法弄清楚如何有效地传递初始化。我需要从ModelForm中子类化一个方法吗?

解决方案

Django 1.4中的新增功能...如果在modelformset上设置初始化现在只适用于额外表单,而不适用于那些绑定到查询器实例的表单:



https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#providing-initial-values



所以上面的各种hack不再是必需的,使用initial是答案。


I have a model formset that I need to pass the keyword initial in to (to have some initial values in the formset, such as date set to today). As far as I can tell, the queryset argument (which defaults to YourModel.objects.all()) overrides this ability for initial empty forms to be created. I specified the queryset as: YourModel.objects.none(), which prevents it from filling in the formset with entries from the database, but I still can't figure out how to pass initial in effectively. Do I need to subclass a method from ModelForm?

解决方案

New in Django 1.4 ...if you set initial on a modelformset it now only applies to the 'extra' forms, not those bound to instances from the queryset:

https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#providing-initial-values

So the various hacks above are no longer necessary and using initial is the answer.

这篇关于将初始化传递给Django的ModelFormSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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