Making "friendly" template contexts
デフォルトでは「object_list」にアサインされるんだけど、それがふさわしくない場合は、変更できます.urlpatterns = patterns('', (r'^publishers/$', ListView.as_view( model=Publisher, context_object_name="publisher_list", )), )
Adding extra context
Often you simply need to present some extra information beyond that provided by the generic view. For example, think of showing a list of all the books on each publisher detail page. The DetailView generic view provides the publisher to the context, but it seems there's no way to get additional information in that template. 普通はデフォルトの汎用ビューを使ったらそれ以外の情報は見れないよね?However, there is; you can subclass DetailView and provide your own implementation of the get_context_data method. The default implementation of this that comes with DetailView simply adds in the object being displayed to the template, but you can override it to show more:
でもDetailViewをサブクラス化して、「get_context_data」メソッドをオーバーライドすれば可能だよ.
from django.views.generic import DetailView
from books.models import Publisher, Bookclass PublisherDetailView(DetailView):
context_object_name = "publisher"
model = Publisherdef get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super(PublisherDetailView, self).get_context_data(**kwargs)
# Add in a QuerySet of all the books
context['book_list'] = Book.objects.all()
return context
ああ、管理人がやりたかったのはまさにこれだ!