Last active
August 29, 2015 14:25
-
-
Save jiaaro/0d6bc8a6d10932db788a to your computer and use it in GitHub Desktop.
formset example code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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): | |
... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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>"{{ form.object.name }}"</h3> | |
<div class="parent"> | |
{{ form.as_p }} | |
</div> | |
</div> | |
{% endfor %} | |
<div> | |
<button type='submit'>Submit</button> | |
</div> | |
</form> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.forms.formsets import formset_factory | |
from django.http import HttpResponseRedirect | |
from .models import MyModel | |
from annoying.decorators import render_to | |
GROUP_SIZE = 10 | |
@render_to("template.html") | |
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: | |
form.save() | |
# 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