我有两个模型,有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']
但我要问的是,我想从作者模型创建CreateView,并在其中添加名为 books 的字段。我试着像这样编码
class AuthorCreateView(CreateView):
model = Author
template_name = "books/author_create.html"
fields = ['name', 'books']
它显示错误"为作者"指定的未知字段(书籍)。
帮助我掌握,我是django的新人
谢谢:)
答案 0 :(得分:2)
由于Author
模型没有名为books
的字段,因此您无法在AuthorCreateView
字段中添加该字段。
您应该首先创建一个Author
的实例,然后将其作为书籍实例中的作者添加。
实施例
book_instance.authors.add(author_instance)
答案 1 :(得分:1)
现在,它通过使用Form和FormView解决,这是我的代码
这是我的forms.py
class AuthorForm(Form):
name = forms.CharField()
books = forms.ModelMultipleChoiceField(Book.objects.all())
这是我的views.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,你节省了我的一天:)