2011-12-17 6 views
3

django_taggitを使用するブログアプリがあります。私のHomePageViewサブクラスArchiveIndexViewとうまくいきます。django_taggitを使用して特定のタグを持つオブジェクトを一覧表示します

私は以下のリンクを使用したいと思います:http://mysite.com/tag/yellowと私はArchiveIndexViewジェネリッククラスを使い、tag_slugでフィルターをかける変更されたクエリーセットを渡したいと思います。私はホームページと同じテンプレートを使いたいので、これをやりたいマイurls.py

url(r'^$', HomePageView.as_view(paginate_by=5, date_field='pub_date',template_name='homepage.html'), 
    ), 

url(r'^tag/(?P<tag_slug>[-\w]+)/$', 'tag_view'), # I know this is wrong 

である私のviews.pyは私がここに迷ってしまいまし実現、および修正その新しいクラスTagViewPage()を作成する方法を見つけることにいくつかの助けをしたいと思い

class HomePageView(ArchiveIndexView): 
"""Extends the detail view to add Events to the context""" 
model = Entry 

def get_context_data(self, **kwargs): 
    context = super(HomePageView, self).get_context_data(**kwargs) 
    context['events'] = Event.objects.filter(end_time__gte=datetime.datetime.now() 
              ).order_by('start_time')[:5] 
    context['comments'] = Comment.objects.filter(allow=True).order_by('created').reverse()[:4] 
    return context 

ですtag_slugでフィルタリングしてクエリーセットを作成します。

答えて

4

重要なことは、get_querysetメソッドをオーバーライドすることです。クエリーセットには、選択したタグの返されたエントリのみが含まれます。 TagListViewHomePageViewから継承しました。同じコンテキストデータが含まれるようにしました。重要でない場合は、ArchiveIndexViewをサブクラス化することができます。

class TagListView(HomePageView): 
    """ 
    Archive view for a given tag 
    """ 

    # It probably makes more sense to set date_field here than in the url config 
    # Ideally, set it in the parent HomePageView class instead of here. 
    date_field = 'pub_date' 

    def get_queryset(self): 
     """ 
     Only include entries tagged with the selected tag 
     """ 
     return Entry.objects.filter(tags__name=self.kwargs['tag_slug']) 

    def get_context_data(self, **kwargs): 
     """ 
     Include the tag in the context 
     """ 
     context_data = super(TagListView, self).get_context_data(self, **kwargs) 
     context_data['tag'] = get_object_or_404(Tag, slug=self.kwargs['tag_slug']) 
     return context_data 

# urls.py 
url(r'^tag/(?P<tag_slug>[-\w]+)/$', TagListView.as_view(paginate_by=5, template_name='homepage.html')), 
+0

ありがとう、私はいくつかの編集で私のために働いた。 paginate_byとself.kwargs ['tag_slug']を追加する必要があります。また、HomePageViewからサブクラス化する場合は、get_context_data(self、** kwargs)関数を完全に取り除くことができると思います。 – Trewq

+0

私は自分の答えを 'self.kwargs ['tag_slug']'で修正しました。テンプレートコンテキストにタグを必要としない限り、 'get_context_data'メソッドは必須ではありません。この行の代わりに – Alasdair

+0

が必要です。context_data ['tag'] = Tag.objects.get(slug = self.kwargs ['tag_slug'])get_object_or_404 – soField

関連する問題