Last active
October 19, 2017 18:57
-
-
Save cwurld/02e7db711d48154fe1744bb6527c6ee8 to your computer and use it in GitHub Desktop.
Django Container with Items - (e.g. inlineformset_factory)
This file contains hidden or 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.models import inlineformset_factory | |
from django.shortcuts import render | |
def container_with_items(request, container_id): | |
ItemFormSet = inlineformset_factory( | |
models.Container, models.Item, form=forms.InlineItemForm, fk_name='container', extra=1 | |
) | |
# Use this to layout the Item forms | |
helper = forms.ItemFormSetFormHelper() | |
# The container should already exist | |
container = models.Container.objects.get(id=int(container_id)) | |
# The default is to have the formset get the queryset of items. You can over-ride this with the | |
# queryset keyword. You can often avoid this by using Model Meta options such as "ordering" | |
qs = my_get_queryset() | |
# Can also initialize the blank forms using the "initial" keyword | |
initial = {'color': 'red'} | |
if request.method == "POST": | |
formset = ItemFormSet(request.POST, request.FILES, instance=container, initial=initial, queryset=qs) | |
if formset.is_valid(): | |
formset.save() | |
return HttpResponseRedirect(reverse('my_url')) | |
else: | |
formset = ItemFormSet(instance=container, initial=initial, queryset=qs) | |
return render(request, "my_form.html", { | |
'formset': formset, 'helper': helper, 'container': container | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment