预先Django(非模型)表单 [英] Prepopulate Django (non-Model) Form

查看:99
本文介绍了预先Django(非模型)表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据一些信息预先填写django表单中的数据,但不使用ModelForm,所以我不能仅仅设置实例。

I'm trying to prepopulate the data in my django form based on some information, but NOT using ModelForm, so I can't just set the instance.

这似乎应该很简单,但是由于某种原因,我找不到任何文档告诉我如何做到这一点。这是我的形式:

This seems like it should be really easy, but for some reason I can't find any documentation telling me how to do this. This is my form:

class MyForm(forms.Form):
  charfield1 = forms.CharField(max_length=3)
  charfield2 = forms.CharField(max_length=3)
  choicefield = forms.ModelChoiceField(MyModel.objects.all())

我只是在做:

form = MyForm()
form.charfield1 = "foo"
form.charfield2 = "bar"
# a model choice field
form.choicefield = MyModel.objects.get(id=3)

哪些不起作用

推荐答案

尝试:

form = MyForm({'charfield1': 'foo', 'charfield2': 'bar'})

Form 对象的构造函数可以使用字段值字典。这将创建一个绑定的表单,可以用于验证数据并将表单呈现为HTML,并显示数据。请参阅表单API 文档更多细节

The constructor of Form objects can take a dictionary of field values. This creates a bound form, which can be used to validate the data and render the form as HTML with the data displayed. See the forms API documentation for more details.

编辑:

为了完整起见,如果你不想绑定表单,而您只想为某些字段声明初始值,可以使用以下代码:

For the sake of completeness, if you do not want to bind the form, and you just want to declare initial values for some fields, you can use the following instead:

form = MyForm(initial={'charfield1': 'foo', 'charfield2': 'bar'})

请参阅初始值详细信息。

这篇关于预先Django(非模型)表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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