2 forms, 1 view, 2 SQL tables in Django
I am trying to figure out how to post data from two django forms to two separate database tables from the same view . I only need one submit button. While this question got me closer to a solution, I am getting errors and no data is being written to the database. I think this code is actually validating two forms against each other, rather than submitting both forms in one go. Any ideas?
Here's what I've tried:
For one form -> one table. It works, so this is a start.
# views.py
def BookFormView(request):
if request.method == 'POST':
form = BookForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect("/books/")
else:
form = BookForm()
return render(request, 'books/createbooks.html',
{'form' : form})
However, when I add this form from a .py form to get subsequent views.py I get local variable 'book_form' referenced before assignment
. This is usually an easy problem with the vs-local global variable to fix, but I don't know what that means in this case.
def BookFormView(request):
if request.method == 'POST':
if 'book' in request.POST:
book_form = BookForm(request.POST, prefix='book')
if book_form.is_valid():
book_form.save()
return HttpResponseRedirect("/books/")
bookdetailsform = BookDetailsForm(prefix='bookdetails')
elif 'bookdetails' in request.POST:
bookdetailsform = BookDetailsForm(request.POST, prefix='bookdetails')
if bookdetailsform.is_valid():
bookdetailsform.save()
return HttpResponseRedirect("/books/")
book_form = BookForm(prefix='book')
else:
book_form = BookForm(prefix='book')
bookdetailsform = BookDetailsForm(prefix='bookdetails')
return render(request, 'books/createbook.html',
{'book_form' : book_form,
'bookdetailsform': bookdetailsform})
source to share
Based on comments:
def BookFormView(request):
if request.method == 'POST':
book_form = BookForm(request.POST, prefix='book')
bookdetailsform = BookDetailsForm(request.POST, prefix='bookdetails')
if book_form.is_valid() and bookdetailsform.is_valid():
book_form.save()
bookdetailsform.save()
return HttpResponseRedirect("/books/")
else:
book_form = BookForm(prefix='book')
bookdetailsform = BookDetailsForm(prefix='bookdetails')
return render(request, 'books/createbook.html',
{'book_form': book_form, 'bookdetailsform': bookdetailsform})
source to share
I think the problem is that when the user submits a post request bookdetails
,
it will be processed in if 'book' in request.POST:
. Why?
because the string bookdetails
contains a string book
, regardless of the request type, it will be conditionally processed if book in request.POST:
.
I believe that fixing what if the condition is the first step.
source to share