Last active
June 12, 2018 06:04
-
-
Save taranjeet/bf3a42ee8bc682d023fbe4c6efd9c376 to your computer and use it in GitHub Desktop.
Django Library: Create Book with Author view
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
# 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