Sometimes, we want to populate initial values on Python Django forms.
In this article, we’ll look at how to populate initial values on Python Django forms.
How to populate initial values on Python Django forms?
To populate initial values on Python Django forms, we can create a form instance with the initial
argument set.
For instance, we write
def view(request):
game = Game.objects.get(id=1) # just an example
data = {'id': game.id, 'position': game.position}
form = UserQueueForm(initial=data)
return render_to_response('my_template.html', {'form': form})
in the view
view function.
In it, we create the UserQueueForm
with the initial
argument set to the data
dict to set the initial value of the form fields with name id
and position
.
And then we call render_to_response
with the template path and a dict with the form
in it.
Then in my_template.html, we render it with
{{ form }}
Conclusion
To populate initial values on Python Django forms, we can create a form instance with the initial
argument set.