Skip to content Skip to sidebar Skip to footer

2 Forms, 1 View, 2 Sql Tables In Django

I'm struggling to understand how to submit data from two django forms into two separate database tables from the same view. I only want one submit button. While this question got m

Solution 1:

Based on the question's 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})

Solution 2:

I think the problem is that when a user submits a bookdetails post request, it will be handled under if 'book' in request.POST: condition. Why? because string bookdetails contains string book, no matter the type of request they do, it will be handled with if book in request.POST: condition.

I believe fixing that if condition problem is the first step.

Post a Comment for "2 Forms, 1 View, 2 Sql Tables In Django"