Field.initial
The initial
argument lets you specify the initial value to use when rendering this Field
in an unbound Form
.
To specify dynamic initial data, see the Form.initial
parameter.
The use-case for this is when you want to display an “empty” form in which a field is initialized to a particular value. For example:
>>> from django import forms >>> class CommentForm(forms.Form): ... name = forms.CharField(initial='Your name') ... url = forms.URLField(initial='http://') ... comment = forms.CharField() >>> f = CommentForm(auto_id=False) >>> print(f) <tr><th>Name:</th><td><input type="text" name="name" value="Your name" required /></td></tr> <tr><th>Url:</th><td><input type="url" name="url" value="http://" required /></td></tr> <tr><th>Comment:</th><td><input type="text" name="comment" required /></td></tr>
You may be thinking, why not just pass a dictionary of the initial values as data when displaying the form? Well, if you do that, you’ll trigger validation, and the HTML output will include any validation errors:
>>> class CommentForm(forms.Form): ... name = forms.CharField() ... url = forms.URLField() ... comment = forms.CharField() >>> default_data = {'name': 'Your name', 'url': 'http://'} >>> f = CommentForm(default_data, auto_id=False) >>> print(f) <tr><th>Name:</th><td><input type="text" name="name" value="Your name" required /></td></tr> <tr><th>Url:</th><td><ul class="errorlist"><li>Enter a valid URL.</li></ul><input type="url" name="url" value="http://" required /></td></tr> <tr><th>Comment:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="comment" required /></td></tr>
This is why initial
values are only displayed for unbound forms. For bound forms, the HTML output will use the bound data.
Also note that initial
values are not used as “fallback” data in validation if a particular field’s value is not given. initial
values are only intended for initial form display:
>>> class CommentForm(forms.Form): ... name = forms.CharField(initial='Your name') ... url = forms.URLField(initial='http://') ... comment = forms.CharField() >>> data = {'name': '', 'url': '', 'comment': 'Foo'} >>> f = CommentForm(data) >>> f.is_valid() False # The form does *not* fall back to using the initial values. >>> f.errors {'url': ['This field is required.'], 'name': ['This field is required.']}
Instead of a constant, you can also pass any callable:
>>> import datetime >>> class DateForm(forms.Form): ... day = forms.DateField(initial=datetime.date.today) >>> print(DateForm()) <tr><th>Day:</th><td><input type="text" name="day" value="12/23/2008" required /><td></tr>
The callable will be evaluated only when the unbound form is displayed, not when it is defined.
Please login to continue.