為Class based view添加額外的內容

在使用cbv時有時會希望在預設的內容外添加額外的內容,這個時後可以get_context_data()方法。

如django官網的範例所示:

from django.views.generic import DetailView
from books.models import Publisher, Book

class PublisherDetail(DetailView):

model = Publisher

def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super(PublisherDetail, self).get_context_data(**kwargs)
# Add in a QuerySet of all the books
context['book_list'] = Book.objects.all()
return context

以上方為例,在將內容加入後,便可以在template處以{{book_list}}的方式調用新加入的內容。

reference:

https://docs.djangoproject.com/en/1.10/topics/class-based-views/generic-display/

Show your support

Clapping shows how much you appreciated Epicure1709’s story.