Reputation: 673
I would like to have a form containing three times two related fields (A name, and some ip address as a simple regex field)
name1
name1 IPs
name2
name2 IPs
name3
name3 IPs
name 1 and 2 are required, IPs are never. Is there a way not to repeat these fields, and/or better, to receive them as list or something like : [ { name, ip }, { name, ip }, { name, ip } ]
EDIT: Name and IPs are wild datas, they are not related to any model, they're used for a call to an API
Thanks
Upvotes: 2
Views: 2340
Reputation: 1155
It seems you have forms and you want to repeat those forms right...
You can use formsets... (formset documentation).
>>> import datetime
>>> from django.forms import formset_factory
>>> from myapp.forms import ArticleForm
>>> ArticleFormSet = formset_factory(ArticleForm, extra=2)
>>> formset = ArticleFormSet(initial=[
... {'title': 'Django is now open source',
... 'pub_date': datetime.date.today(),}
... ])
>>> for form in formset:
... print(form.as_table())
You can send this formset as a context variable to render the template with these forms.
In the template.html
<form method="post" action="">
{{ formset.management_form }}
<table>
{% for form in formset %}
{{ form }}
{% endfor %}
</table>
<button type="submit">
</form>
That should work
Upvotes: 1
Reputation: 1559
You need to use inline formsets.
Creating a model and related models with Inline formsets
https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#inline-formsets
Upvotes: 1