Skip to content

Instantly share code, notes, and snippets.

@jiaaro jiaaro/
Last active Aug 29, 2015

What would you like to do?
formset example code
class MyForm(forms.Form):
is_interesting = forms.BooleanField(required=False)
def __init__(self, *args, **kwargs):
self.object = kwargs['initial']['obj']
super(MyForm, self).__init__(*args, **kwargs)
def save(self):
<form action='.' method='POST'>
{{ formset.management_form }}
{% if formset.errors %}
<ul class='errorlist'><li>There are Errors. Details below...</li></ul>
{% endif %}
{% for form in formset %}
<div class="subform">
{# NOTE: form.object is a MyModel instance #}
<h3>"{{ }}"</h3>
<div class="parent">
{{ form.as_p }}
{% endfor %}
<button type='submit'>Submit</button>
from django.forms.formsets import formset_factory
from django.http import HttpResponseRedirect
from .models import MyModel
from annoying.decorators import render_to
def my_view(request, rel_obj_id=None):
queryset = MyModel.objects.filter(…).order_by('id')
MyFormSet = formset_factory(MyForm, extra=0)
formset = MyFormSet(request.POST or None, initial=[{'obj': obj} for obj in queryset[:GROUP_SIZE]])
if formset.is_valid():
for form in formset:
# load the page fresh (easier than making a new, empty formset)
return HttpResponseRedirect(request.path)
return locals()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.