Forms Part 4: Formsets

Formsets make life easier when it comes to dealing with multiple forms of the same type on the same page. In this episode we will show you how to set them up, and the basics of how to save that data to the database. It is not much different from dealing with single forms.

Resources

views.py
from django.shortcuts import 
from django.template import RequestContext
from django.forms.formsets import formset_factory

from contact.forms import 

def interview(request):
    QuestionFormSet = formset_factory(QuestionForm, extra=5)
    if request.method == "POST":
        formset = QuestionFormSet(request.POST)

        if(formset.is_valid()):
            message = "Thank you"
            for form in formset:
                print form
                form.save()
        else:
            message = "Something went wrong"

        return render_to_response('contact/interview.html',
                {'message': message},
                context_instance=RequestContext(request))
    else:
        return render_to_response('contact/interview.html',
                {'formset': QuestionFormSet()},
                context_instance=RequestContext(request))
Template
{% extends "base.html" %}

{% block content %}
You only get 5 questions so ask wisely.
{% if message %}
  {{ messsage }}
{% endif %}
<div>
  <form action="/interview/" method="post">{% csrf_token %}
    {{ formset.management_form }}

    {% for form in formset %}
      {{ form.as_p }}
    {% endfor %}
    <input type="submit" value="Submit Questions" />
  </form>
</div>
{% endblock %}

comments powered by Disqus