【问题标题】:Django ManyToMany CreateView Fields In Both Tables两个表中的 Django ManyToMany CreateView 字段
【发布时间】:2017-07-11 19:22:29
【问题描述】:

我有两个模型,有 Book 和 Author,我在 Book 模型中添加了 ManyToMany 字段

class Author(models.Model):
    name = models.CharField(verbose_name='name', max_length=50)
    created_at = models.DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return unicode(self.name)    

class Book(models.Model):
    title = models.CharField(verbose_name='title', max_length=50)
    authors = models.ManyToManyField(Author) # Many to many
    created_at = models.DateTimeField(auto_now_add=True)    

    def __unicode__(self):
        return unicode(self.title)

如果我想从书籍和访问作者创建 CreateView,我可以添加这样的代码

class BookCreateView(CreateView):
    model = Book
    template_name = "books/book_create.html"
    fields = ['title', 'authors'] 

但我想问的是我想从 Author 模型创建 CreateView 并在其中添加名为 books 的字段。我试着像这样写代码

class AuthorCreateView(CreateView):
    model = Author
    template_name = "books/author_create.html"
    fields = ['name', 'books']

并显示错误“为作者指定的未知字段(书籍)”。

各位高手帮帮我,我是 django 新手

谢谢:)

【问题讨论】:

    标签: python django many-to-many create-view


    【解决方案1】:

    由于Author 模型没有名为books 的字段,因此您无法将其添加到AuthorCreateView 字段中。

    您应该首先创建一个Author 的实例,然后将它们作为作者添加到书籍实例中。

    示例。

    book_instance.authors.add(author_instance)
    

    【讨论】:

    • 用什么方法?
    • 这取决于您要构建的内容。
    【解决方案2】:

    现在,用Form和FormView解决了,这是我的代码

    这是我的forms.py

    class AuthorForm(Form):
        name = forms.CharField()
        books = forms.ModelMultipleChoiceField(Book.objects.all())
    

    这是我的观点.py

    class AuthorCreateView(FormView):
        template_name = "books/author_create.html"
        form_class = AuthorForm
    
        def form_valid(self, form):
            name = form.cleaned_data['name']
            books = form.cleaned_data['books']
    
            author = Author(name=name)
            author.save()
            book_list = Book.objects.filter(pk__in=books)
            for book in book_list:
                author.book_set.add(book)
    
            return HttpResponse(author.book_set.all())
    

    顺便说一句,谢谢@kartikmaji,你拯救了我的一天:)

    【讨论】:

      猜你喜欢
      • 2020-02-18
      • 1970-01-01
      • 2015-05-15
      • 2019-05-07
      • 2017-05-04
      • 2017-03-21
      • 1970-01-01
      • 2013-10-21
      • 2015-10-25
      相关资源
      最近更新 更多