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 :)
Since
Author
model don't have a field namedbooks
, you cannot add that inAuthorCreateView
fields.What you should do is first create an instance of
Author
and then add them as author in books instance.Example.
Now, it is solved by using Form and FormView, this is my code
this is my forms.py
this is my views.py
btw thanks @kartikmaji , you have saved my day :)