[Answer]-Display Two Forms in one Template in Django

1👍

Formsets are overkill for two forms. This is actually not too hard but poorly documented. You can make both forms the same form type, just give a prefix.

def parent_apply(request):
  if request.method == 'POST':
    parent_form = SignupForm(request.POST, prefix="parent")
    student_form = StudentApplyForm(request.POST, prefix="student")
    if parent_form.is_valid() and student_form.is_valid():
      parent = parent_form.save()
      student = student_form.save(parent)
    else: messages.error(request, "Please correct the errors marked in red.")
  else:
    parent_form = SignupForm(prefix="parent")
    student_form = StudentApplyForm(prefix="student")

  return render_to_response('template_path/forms.html', { 'parent_form':parent_form, 'student_form':student_form }, context_instance=RequestContext(request))

The forms are just regular Django forms, no special settings required. You can change the order on which they validate and save one even if the other did not validate if you choose.

In your HTML Template, wrap both forms in the same tag and they will submit at the same time. If you want your forms to go to different view functions, specify two different elements.

0👍

Thanks for all the help. The pointers really helped me come to this solution. The main change was to ‘def get’ as shown below. I dropped the formset and passed the forms this way.

def get(self, request, *args, **kwargs):
     form = self.settings_form_class
     formset = self.default_form_class

     return self.render_to_response(self.get_context_data(form = form, formset = formset))

I was unaware this was possible! Thanks again.

Leave a comment