两个表中的Django ManyToMany CreateView字段

编程入门 行业动态 更新时间:2024-10-10 19:23:37
本文介绍了两个表中的Django ManyToMany CreateView字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I have two models, there are Book and Author and I add ManyToMany field inside Book model

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并访问作者,则可以添加这样的代码

If I want to create CreateView from book and access authors, I can just add code like this

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

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

but something that I want to ask is I want to create CreateView from Author model and add field named books inside it. I tried to code like this

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

,它显示错误为作者指定了未知字段(书)".

and it shows an error "Unknown field(s) (books) specified for Author".

帮助我的主人,我是django的新手

help me masters, I'm new in django

谢谢:)

推荐答案

由于Author模型没有名为books的字段,因此无法在AuthorCreateView字段中添加该字段.

Since Author model don't have a field named books, you cannot add that in AuthorCreateView fields.

您应该做的是首先创建Author的实例,然后将其添加为book实例中的作者.

What you should do is first create an instance of Author and then add them as author in books instance.

示例.

book_instance.authors.add(author_instance)

更多推荐

两个表中的Django ManyToMany CreateView字段

本文发布于:2023-07-14 10:32:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1104118.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   两个   ManyToMany   Django   CreateView

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!