Advertisement
seanmavley

inlineformset_factory editing

Apr 23rd, 2015
435
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.99 KB | None | 0 0
  1. def edit_books(request, author_id):
  2.     author = Author.objects.get(pk=author_id)
  3.     author_form = AuthorModelForm(instance=author)
  4.     BookInlineFormSet = inlineformset_factory(Author, Book, fields=('title',))
  5.  
  6.     if request.method == "POST":
  7.         author_form = AuthorModelForm(request.POST)
  8.         formset = BookInlineFormSet(request.POST, request.FILES, instance=author)
  9.  
  10.         if author_form.is_valid():
  11.             created_author = author_form.save(commit=False)
  12.             formset = BookInlineFormSet(request.POST, request.FILES, instance=created_author)
  13.  
  14.             if formset.is_valid():
  15.                 created_author.save()
  16.                 formset.save()
  17.                 return HttpResponseRedirect(created_author.get_absolute_url())
  18.     else:
  19.         author_form = AuthorModelForm(instance=author)
  20.         formset = BookInlineFormSet(instance=author)
  21.  
  22.     return render(request, "edit_books.html", {
  23.         "author_form": author_form,
  24.         "formset": formset,
  25.     })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement