Django ManyToMany CreateView Fields In Both Tables

2019-09-14 10:06发布

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)

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'] 

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".

help me masters, I'm new in django

Thanks :)

2条回答
该账号已被封号
2楼-- · 2019-09-14 10:45

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

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

Example.

book_instance.authors.add(author_instance)
查看更多
The star\"
3楼-- · 2019-09-14 10:47

Now, it is solved by using Form and FormView, this is my code

this is my forms.py

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

this is my 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())

btw thanks @kartikmaji , you have saved my day :)

查看更多
登录 后发表回答