2

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

mmeisson
  • 623
  • 6
  • 22

2 Answers2

1

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

Community
  • 1
  • 1
zubhav
  • 1,519
  • 1
  • 13
  • 19
  • I'm sorry, but I don't understand. There is actually no models related to this form (cause I use these datas with an API). – mmeisson Jan 09 '17 at 11:42
1

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

Rahul Reddy Vemireddy
  • 1,149
  • 1
  • 10
  • 14