Django Form“初始"和“绑定数据"之间的区别? [英] Difference between Django Form 'initial' and 'bound data'?

查看:22
本文介绍了Django Form“初始"和“绑定数据"之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

举一个这样的例子:

class MyForm(forms.Form): 
    name = forms.CharField()

我试图了解以下两个片段之间的区别:

I'm trying to grasp what the difference between the following two snippets is:

绑定数据"样式:

my_form = MyForm({'name': request.user.first_name})

初始数据"样式:

my_form = MyForm(initial={'name': request.user.first_name})

文档似乎暗示初始值用于动态初始值",但能够将绑定数据"传递给构造函数完成了完全相同的事情.我过去曾将初始数据用于动态值,但我很想使用更直接的绑定数据"样式,但想了解一下这两种样式之间的真正区别是什么.

The documentation seems to suggest than "initial is for dynamic initial values", and yet being able to pass "bound data" to the constructor accomplishes exactly the same thing. I've used initial data in the past for dynamic values, but I'm tempted to use the more straightforward "bound data" style, but would like some insights about what the real difference between these two styles is.

推荐答案

这是 绑定和未绑定表单.

表单实例要么绑定到一组数据,要么未绑定:

A Form instance is either bound to a set of data, or unbound:

  • 如果它绑定到一组数据,它能够验证该数据并将表单呈现为 HTML,并在 HTML 中显示数据.
  • 如果它未绑定,则无法进行验证(因为没有要验证的数据!),但仍可以将空白表单呈现为 HTML.
  • If it’s bound to a set of data, it’s capable of validating that data and rendering the form as HTML with the data displayed in the HTML.
  • If it’s unbound, it cannot do validation (because there’s no data to validate!), but it can still render the blank form as HTML.

您无法真正看到您提供的示例表单的差异,因为该表单在绑定数据"中有效;风格.我们来扩展一下表单,添加一个age字段,这样区别会更明显.

You can't really see the difference for the example form you gave, because the form is valid in the "bound data" style. Let's extend the form by adding an age field, then the difference will be more obvious.

class MyForm(forms.Form):
    name = forms.CharField()
    age = forms.IntegerField()

绑定形式

my_form = MyForm({'name': request.user.first_name})

此表格无效,因为未指定age.当您在模板中呈现表单时,您将看到 age 字段的验证错误.

This form is invalid, because age is not specified. When you render the form in the template, you will see validation errors for the age field.

my_form = MyForm(initial={'name':request.user.first_name})

此表格未绑定.不会触发验证,因此渲染模板时不会显示任何错误.

This form is unbound. Validation is not triggered, so there will not be any errors displayed when you render the template.

这篇关于Django Form“初始"和“绑定数据"之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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