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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…