× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Different initial values in a Django formset

Viorel Stirbu
Feb 02, 2015
<p>If you have several forms created using django formset and you need different initial values for each of them then you can pass an array of dictionaries as argument to the formset constructor. You can use a <span style="color:rgb(95, 99, 102)">for comprehension or </span>generator for that:</p> <pre><code class="language-python">class ArticleForm(forms.Form): title = forms.CharField() pub_date = forms.DateField() ArticleFormSet = formset_factory(ArticleForm, extra=1) formset = ArticleFormSet(initial=[{'title': "Form %d" % (i+1), 'pub_date': datetime.date.today()} for i in range(10)])</code></pre> <p>This will generate a form like:</p> <div style="background:#eee;border:1px solid #ccc;padding:5px 10px;">Title: [Form 1] Pub date: [2015-02-02]</div> <div style="background:#eee;border:1px solid #ccc;padding:5px 10px;">Title: [Form 2] Pub date: [2015-02-02]</div> <div style="background:#eee;border:1px solid #ccc;padding:5px 10px;">...</div> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus