0

I saw that you could use the screen to record several forms together, in my example I would like to respond to several questions in the same time. I choose my questions and I answer my valid but it does not record that whenever the last form ... How can I do to make it records all the information in the same time ? It registers in my database only the last form every time ...

So i have a forms like that :

class NameForm(forms.ModelForm):
    class Meta:
        model = Reply
        fields = ('question','user','answer')

a views.py :

def get_name(request):
    questions = Question.objects.all()
    NameFormSet = modelformset_factory(model=Reply, form=NameForm, extra=2, max_num=2)
    logged_user = get_logged_user_from_request(request)
    if request.method == 'POST':  
        formset = NameFormSet(request.POST, request.FILES)
        if formset.is_valid():
            formset.save()
            return HttpResponse('Successfully')
        else:
            return render_to_response('polls/name.html')
    else:
        formset = NameFormSet()
    return render_to_response('polls/name.html', {'formset': formset, 'questions':questions,'logged_user':logged_user})

And for finish my template :

<form method="post" action="">
    <table>
        {{ formset }}
    </table>

     <input type="submit" value="Submit" />
</form>

What I forget to put it records all my forms at the same time?

Jérémy Legendre
  • 255
  • 1
  • 4
  • 17

1 Answers1

0

I'll try to give you a correct approach to do that (I won't test the code I give you).

You should try to define an array of forms in views :

questions = Question.objects.all()
form_list = []
if request.POST:
    for question in questions:
        current_form = NameForm(request.POST, instance=question)
        if current_form.is_valid():
            current_form.save()
            return HttpResponse('Successfully')
else:
    for question in questions:
        form_list.append(NameForm(instance=question))

And display all forms in template :

<form method="post" action="">
    {% for form in form_list %}
            <table>
                {{ form.asp_p }}
            </table>
    {% endfor %}
    <input type="submit" value="Submit" />
</form>

If you want more details :

self.instance in Django ModelForm

django submit two different forms with one submit button

Community
  • 1
  • 1
Samuel Dauzon
  • 10,744
  • 13
  • 61
  • 94