2个表单,1个视图,2个Django中的SQL表 [英] 2 forms, 1 view, 2 SQL tables in Django
问题描述
我很难理解如何将数据从两个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 me closer to the solution, I'm getting errors and the data is not writing to the database. I think this code actually checks the two forms against each other instead of submitting both forms in one go. Any ideas?
这是我试过的:
对于一个表单 - >一个表。这样做,所以这是一个开始。
For one form --> one table. This works, so it's 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})
但是,当我从forms.py中添加此表单以获取后续的views.py时,我得到局部变量' book_form'在分配前引用
。这通常是一个简单的全局vs局部变量问题来解决,但我不知道在这种情况下是什么意思。
However, when I add this form in from forms.py to get the subsequent views.py I get local variable 'book_form' referenced before assignment
. That's usually an easy global-vs-local variable issue to fix, but I don't know what it 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})
推荐答案
根据问题的意见:
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})
这篇关于2个表单,1个视图,2个Django中的SQL表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!