Skip to content

Instantly share code, notes, and snippets.

@taranjeet
Last active June 12, 2018 06:04
Show Gist options
  • Save taranjeet/bf3a42ee8bc682d023fbe4c6efd9c376 to your computer and use it in GitHub Desktop.
Save taranjeet/bf3a42ee8bc682d023fbe4c6efd9c376 to your computer and use it in GitHub Desktop.
Django Library: Create Book with Author view
# views.py :: part 2
def create_book_with_authors(request):
template_name = 'store/create_with_author.html'
if request.method == 'GET':
bookform = BookModelForm(request.GET or None)
formset = AuthorFormset(queryset=Author.objects.none())
elif request.method == 'POST':
bookform = BookModelForm(request.POST)
formset = AuthorFormset(request.POST)
if bookform.is_valid() and formset.is_valid():
# first save this book, as its reference will be used in `Author`
book = bookform.save()
for form in formset:
# so that `book` instance can be attached.
author = form.save(commit=False)
author.book = book
author.save()
return redirect('store:book_list')
return render(request, template_name, {
'bookform': bookform,
'formset': formset,
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment