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

查看:21
本文介绍了预填充 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天全站免登陆