Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

python - Difference between Django Form 'initial' and 'bound data'?

Given an example like this:

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

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

"Bound Data" style:

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

"Initial data" style:

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's the key part from the django docs on bound and unbound forms.

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

  • 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.

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()

Bound form

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

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.

Unbound form with dynamic initial data

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...