我很难理解如何将两个django表单中的数据从相同的视图提交到两个单独的数据库表中。我只想要一个提交按钮。虽然this问题使我更接近解决方案,但我收到错误并且数据没有写入数据库。我认为这段代码实际上是相互检查两种形式,而不是一次性提交两种形式。有什么想法吗?
以下是我尝试的内容:
对于一种形式 - >一张桌子。这是有效的,所以它是一个开始。
# 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})
但是,当我从forms.py中添加此表单以获取后续的views.py时,我得到local variable 'book_form' referenced before assignment
。这通常是一个容易修复的全局与局部变量问题,但我不知道在这种情况下它意味着什么。
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})
答案 0 :(得分:1)
根据问题的评论:
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})
答案 1 :(得分:0)
我认为问题在于,当用户提交bookdetails
帖子请求时,
它将在if 'book' in request.POST:
条件下处理。为什么呢?
因为字符串bookdetails
包含字符串book
,所以无论它们的请求类型如何,它都将以if book in request.POST:
条件处理。
我相信如果条件问题是第一步,那就解决这个问题。