Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Access Many to many field in class based views in Django?

I have two models, Author & Book in models.py

class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    email = models.EmailField()
    age = models.IntegerField()

def __str__(self):
    return '%s %s' %(self.first_name, self.last_name)

def __unicode__(self):
    return '%s %s' %(self.first_name, self.last_name)



class Book(models.Model):
    title = models.CharField(max_length=100) #name = title
    pages = models.IntegerField()
    price = models.DecimalField(max_digits=10, decimal_places=2)
    rating = models.FloatField()
    author = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher)
    publication_date = models.DateField()

def __str__(self):
    return self.title

def __unicode__(self):
    return self.title

Now i'm listing all the books using ListView. And on click of a book i'm getting information the book using following method

class BookDetailView(generic.DetailView):
    template_name = 'books/book_detail1.html'
    model = Book
    context_object_name = 'book_detail' 

I'm able to access title, pages, price, rating, publisher & publication_date but not getting all the Authors(Author list). While i'm going to simply print it, it prints None in template. I even try to iterate using For Loop but not done in template

views.py

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<ul>
    <li>Price:{{ book_detail.price }}</li>  
    <li>Pub Date:{{ book_detail.publication_date }}</li>
    <li>Title: {{ book_detail.title }}</li>
    <li>Pages: {{ book_detail.pages }}</li> 
    <li>Rating: {{ book_detail.rating }}</li>
    <li>Publisher: {{ book_detail.publisher }}</li>
    <li>Author: {{ book_detail.author }}</li>   
</ul>

</body>
</html>

Can anyone help me to out from this?

like image 901
Pinank Lakhani Avatar asked Oct 22 '25 06:10

Pinank Lakhani


1 Answers

You have defined a many-to-many relationship between Book and Author which means that a book can have any number of authors. In order to display them you need to loop through the set of authors:

Authors:
<ul>
{% for author in book_detail.author.all %}
    <li>{{ author }}</li>
{% endfor %}
</ul>

You might want to change the name of that field to authors to be less confusing.

Alternatively if you want only one author for a book then you need to use a ForeignKey instead of a ManyToManyField. In that case your existing template logic would work.

like image 154
solarissmoke Avatar answered Oct 23 '25 20:10

solarissmoke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!