Reputation: 455
Using Django, I have created the Book class and the BookManager class in the models.py. The BookManager class has the method to count the number of the book title containing the keyword. How can I show the book title count to the HTML file using the Classe-based view?
I know how to do it using the function-based view but not with the ListView class based view.
models.py
from django.db import models
# Create your models here.
class BookManager(models.Manager):
def title_count(self, keyword):
return self.filter(title__icontains=keyword).count()
class Book(models.Model):
title = models.CharField(max_length=100)
publication_date = models.DateField()
page_length = models.IntegerField(null=True, blank=True)
objects = BookManager()
def __unicode__(self):
return self.title
views.py
from django.shortcuts import render
from django.views.generic import ListView
from .models import Book
class BookViewPage(ListView):
model = Book
title_number = Book.objects.title_count('django')
def bookviewpage(request):
context ={
'count': Book.objects.title_count('django')
}
return render(request, 'books/book_list.html', context)
I want to display the book title count on the HTML file using the Classe-based view.
Upvotes: 2
Views: 1014
Reputation: 308939
You can add items to the context of class based views by overriding the get_context_data
method.
class BookViewPage(ListView):
model = Book
def get_context_data(self, **kwargs):
context = super(BookViewPage, self).get_context_data(**kwargs)
context['title_number'] = Book.objects.title_count('django')
return context
Now you can use {{ title_number }}
in the template.
Putting title_number = Book.objects.title_count('django')
in the view doesn't work, because this code runs when the module is loaded, not when the view handles the request.
Upvotes: 2