如何用一种形式更新两个模型?

时间:2018-11-15 04:08:10

标签: django

我希望用户可以使用一个提交按钮来更新两个模型。第一个模型将容纳用户提交的所有书名(唯一)和页面。另一个将显示哪些用户提交了哪些图书。

理想情况下,我想执行以下操作:

如果request.method ==“ POST”:     形式= AddBookForm(request.POST)

if form.is_valid():
    books = form.save(commit=False)
    ub = UserBooks()

    books.book_title = form.cleaned_data['book_title']
    books.book_total_pages = form.cleaned_data['book_total_pages']

    ub.user = request.user
    ub.book_title = form.cleaned_data['book_title']

    ub.save()
    books.save()

    return redirect('new_book')

但这给了我错误:

  

无法分配“'某些书名'”:“ UserBooks.book_title”必须是   “图书”实例。

用一种形式更新两个模型的最佳方法是什么?

这是其他文件。 models.py

class Books(models.Model):

    created = models.DateTimeField(auto_now_add=True, editable=False)
    last_updated = models.DateTimeField(auto_now=True, editable=False)

    book_title = models.CharField(max_length=100, unique=True)
    book_total_pages = models.IntegerField()


    class Meta:
        ordering = ('-created',)

    def __str__(self):
        return '{0}'.format(self.book_title)


class UserBooks(models.Model):

    user = models.ForeignKey(User, on_delete=models.CASCADE, null=False, blank=False)
    book_title = models.ForeignKey(Books, on_delete=models.CASCADE, null=False, blank=False)

views.py

def new_book(request):
    user = request.user

    if request.method == "POST":
        form = AddBookForm(request.POST)

        if form.is_valid():
            books = form.save(commit=False)
            books.book_title = form.cleaned_data['book_title']
            books.book_total_pages = form.cleaned_data['book_total_pages']
            books.save()

            return redirect('new_book')
    else:
        form = AddBookForm()
    return render(request, 'main/addanewbook.html', {
        'form': form,
        'allBooks': allBooks,
        'userbooks': userbooks,
    })

forms.py

class AddBookForm(forms.ModelForm):
    class Meta:
        model = Books
        fields = ('book_title', 'book_total_pages')

1 个答案:

答案 0 :(得分:4)

您需要在视图中进行一些更改

if form.is_valid():
    books = form.save(commit=False)
    ub = UserBooks()

    books.book_title = form.cleaned_data['book_title']
    books.book_total_pages = form.cleaned_data['book_total_pages']
    books = books.save()
    ub.user = request.user
    ub.book_title = books

    ub.save()


    return redirect('new_book')

这会做到