Introduction
If you need any or all of the fields of a Django Form to be filled with some initial data once you've created it, you can utilize the Django Forms functionality to do so. When the user accesses the form HTML page, this initial form value is immediately triggered. This value can be used as a prefilled form value since it's not a placeholder for the form.
Initial form data in Django forms values
Use initial to declare the initial form value fields at runtime. For example, you could want to use the current session's username in a username field.
Use the form's initial parameter to accomplish this. If given, this argument should be a dictionary that maps field names to their initial values. Include only the fields for which you're providing an initial value; you don't need to include all fields in your form. Consider the following scenario:
f = ContactForm(initial={'subject': 'Hi there!'})
These values are only shown for unbound forms and aren't utilized as fallback values if a specific value isn't provided.
If a Field defines initial and you also include initial in the form's initialization, the latter initial will take precedence.
In this example, initial is specified at both the field and form instance levels, but the latter takes precedence:
from django import forms
class CommentForm(forms.Form):
name = forms.CharField(initial='class')
url = forms.URLField()
comment = forms.CharField()
f = CommentForm(initial={'name': 'instance'}, auto_id=False)
print(f)
<tr><th>Name:</th><td><input type="text" name="name" value="instance" required></td></tr>
<tr><th>Url:</th><td><input type="url" name="url" required></td></tr>
<tr><th>Comment:</th><td><input type="text" name="comment" required></td></tr>
Form.get_initial_for_field(field, field_name)
Returns the initial data for a form field. If Form.initial is present, the data is retrieved from there; otherwise, Field.initial is used. The callable values are examined.
Because BoundField.initial has a simpler interface than get_initial_for_field(), it is preferred over get_initial_for_field(). BoundField.initial caches its values, unlike get_initial_for_field(). This is very useful when working with callables with variable return values (like datetime.now or uuid.uuid4):
import uuid
class UUIDCommentForm(CommentForm):
identifier = forms.UUIDField(initial=uuid.uuid4)
f = UUIDCommentForm()
f.get_initial_for_field(f.fields['identifier'], 'identifier')
UUID('972ca9e4-7bfe-4f5b-af7d-07b3aa306334')
f.get_initial_for_field(f.fields['identifier'], 'identifier')
UUID('1b411fab-844e-4dec-bd4f-e9b0495f04d0')
# Using BoundField.initial, for comparison
f['identifier'].initial
UUID('28a09c59-5f00-4ed9-9179-a3b074fa9c30')
f['identifier'].initial
UUID('28a09c59-5f00-4ed9-9179-a3b074fa9c30')




