I am currently going through the base django documentation as I am trying to come up with some basic edit view class for an old project of mine. For this I have to work with formsets. I am confused at the pattern of calls used within this example for producing an edit view.
What is the exact reason why you have to instantiate the formset for the validation with the request.POST, and for errors you recreate the whole thing again with your initial instance... (Otherwise it won't show any data)
def manage_books(request, author_id):
author = Author.objects.get(pk=author_id)
BookInlineFormSet = inlineformset_factory(Author, Book, fields=('title',))
if request.method == "POST":
formset = BookInlineFormSet(request.POST, request.FILES, instance=author)
if formset.is_valid():
formset.save()
# Do something. Should generally end with a redirect. For example:
return HttpResponseRedirect(author.get_absolute_url())
else:
formset = BookInlineFormSet(instance=author)
return render(request, 'manage_books.html', {'formset': formset})