簡體   English   中英

兩個表中的Django ManyToMany CreateView字段

[英]Django ManyToMany CreateView Fields In Both Tables

我有兩個模型,分別是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的新手

謝謝 :)

由於Author模型沒有名為books的字段,因此無法在AuthorCreateView字段中添加該字段。

您應該做的是首先創建一個Author實例,然后將其添加為books實例中的author。

例。

book_instance.authors.add(author_instance)

現在,通過使用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,您保存了我的一天:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM