Remind Me: Initial Data in a Django class-based Form
I love Django’s class-based way of handling forms. You name the class, articulate each field (data point of your form), and attach it to a view. Voila. But what happens when you want some initial data in the form?
Initial to the rescue!
What your class might look like:
class PersonForm(forms.Form): first_name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) gender = forms.CharField(max_length=1) hair_color = forms.CharField(max_length=256)
If you now wanted to initialize your form for males with blonde hair, include this snippet in your view:
form = PersonForm(initial = { ‘gender’ : “M”, ‘hair_color’ : “blonde” } )
Then pass that form as part of your render return:
return render_to_response(‘add_person.htm’, { ‘form’ : form })
This post is brought to you by #neverwantingtosearchtheinternetforthisagain, and StackOverflow for inspiration.