Skip to content

Instantly share code, notes, and snippets.

@taranjeet
Created June 12, 2018 05:57
Show Gist options
  • Save taranjeet/f0f6f3b2b365ea3f94195306a0de1214 to your computer and use it in GitHub Desktop.
Save taranjeet/f0f6f3b2b365ea3f94195306a0de1214 to your computer and use it in GitHub Desktop.
Django Library: Create Book View
# views.py :: part 2
from django.shortcuts import render, redirect
from .forms import BookFormset
from .models import Book
def create_book_normal(request):
template_name = 'store/create_normal.html'
heading_message = 'Formset Demo'
if request.method == 'GET':
formset = BookFormset(request.GET or None)
elif request.method == 'POST':
formset = BookFormset(request.POST)
if formset.is_valid():
for form in formset:
# extract name from each form and save
name = form.cleaned_data.get('name')
# save book instance
if name:
Book(name=name).save()
# once all books are saved, redirect to book list view
return redirect('book_list')
return render(request, template_name, {
'formset': formset,
'heading': heading_message,
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment