Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Multiple instances of same form class in one view

In the context of Django Forms, I've seen many discussions of handling different kinds of forms on the same page (eg AForm and BForm on the same page), but I'm trying to figure how to handle multiple instances of the same form class on a page.

I am able to display the forms alright, but I don't know how to handle them when the forms are POSTed.

I've tried using Formsets as well, and have the same issue (can display, but don't know how to handle POST).

So here's my question: let's say I'm displaying several instances of the same Form class on a page. How would I go about handling the POST data when these forms are submitted?

Edit:

Problem with formset is that I have a custom Form and have found it difficult to use formset to handle POST data.

Edit 2 - providing more details given @neverwalkaloner's response.

Here's my form class:

class QuestionForm(forms.Form):
def __init__(self, question, data=None, *args, **kwargs):
    super(QuestionForm, self).__init__(*args, **kwargs)
    choice_list = [x for x in question.get_answers_list()]
    self.fields['answers'] = forms.ChoiceField(choices=choice_list,
                                            widget=RadioSelect)

    self.fields['answers'].label = question.content

I'm creating different forms with a prefix like so: form = QuestionForm(question=question, prefix=prefix)

Then, handling POST data like so: form = QuestionForm(data=request.POST, question=question, prefix=prefix)

However, the forms do not bind with the above approach :(

like image 274
John Avatar asked Oct 23 '25 16:10

John


1 Answers

You can use prefix argument to initialize multiple forms in your view:

mother = PersonForm(request.POST, prefix="mother")
father = PersonForm(request.POST, prefix="father")

return render(request, 'some_template.html', {
    'mother': mother,
    'father': father,
})
like image 113
neverwalkaloner Avatar answered Oct 25 '25 06:10

neverwalkaloner