0

I have a model and i need to create form with multiple instances in it. To be more specific: i need to render my ModelForm inside regular form with square brackets next to it's fields names. Something like this in magicworld:

forms.py

class ManForm(ModelForm):
    class Meta:
        model = Man
        fields = ['name', 'age']

class PeopleForm(forms.Form):
    # modelless form
    people = ??? # array of ManForm instances or something

form.html

<form action="/people/create/">
    {{ form }}
</form>

output

<form action="/people/create/">
    <input type="text" name="name[0]"/>
    <input type="text" name="age[0]"/>
</form>

To tell you the truth, i don't know how to approach this problem at all. I tried modelformset_factory, but all i've got is <input type="text" name="form-0-name"/>

4
  • Can you explain why you think you need that specific format, rather than the one that Django formsets use? Commented Jan 31, 2017 at 13:04
  • i need to iterate over each man in view.py and perform specific task Commented Jan 31, 2017 at 13:16
  • Yes, that is what a formset does. So why can't you use one? Commented Jan 31, 2017 at 13:23
  • it seems that i don't know how to iterate over formsets in view Commented Jan 31, 2017 at 13:29

2 Answers 2

1

As discussed in the comments, you need a formset.

def create_people(request):
    PeopleFormSet = modelformset_factory(Man, form=ManForm)
    if request.method == 'POST':
        formset = PeopleFormSet(request.POST)
        if formset.is_valid():
            for form in formset:
                ... do something with individual form
    else:
        formset = PeopleFormSet()
    return render(request, template_name, {'formset': formset}
Sign up to request clarification or add additional context in comments.

1 Comment

I didn't know that request.POST parses formsets that way. Thanks
0

For using formsets in function based views see @Daniel Roseman 's answer or read up here.

For class based views there is no built in generic view for this. According to this ticket they decided to let third-party-packages handle that. You can use django-extra-views for that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.