Search code examples
pythondjangokeyword-argumentdjango-taggit

Django-taggit kwargs understanding


I'm using-django taggit and it works fine. But there are need to make some changes to extend DetailView url and after them TagListView chushed with 404 error. So i'm undestand that problem with kwargs in get_absolute_url function, but i can't understand how to fix it.

So, work fine: models.py

    def get_absolute_url(self):
       return reverse("posts:detail", kwargs={"slug": self.slug})

urls.py:

    url(r'^(?P<slug>[\w-]+)/$', Detail.as_view(), name='detail'),
    url(r'^tag/(?P<slug>[\w-]+)/$', TagListView.as_view(), name='tagged'),

views.py:

class TagListView(ListView):
   template_name = "posts/postlist.html"
   paginate_by = "3"

   def get_queryset(self):
      return Post.objects.filter(tags__slug=self.kwargs.get("slug")).all()

   def get_context_data(self, **kwargs):
       context = super(TagListView, self).get_context_data(**kwargs)
       context["tag"] = self.kwargs.get("slug")
       return context

And when I add "category": self.category to get_absolute_url and urls it crush:

models.py:

def get_absolute_url(self):
       return reverse("posts:detail", kwargs={"category": self.category, "slug": self.slug})

urls.py:

    url(r'^(?P<category>[\w-]+)/(?P<slug>[\w-]+)/$', Detail.as_view(), name='detail'),
    url(r'^tag/(?P<slug>[\w-]+)/$', TagListView.as_view(), name='tagged'),

I suppose that there shoulb be changes in get_context_data func, but can't see what exactly. Any ideas or advices please?


Solution

  • So I resolve problem by changing urls order to:

        url(r'^tag/(?P<slug>[\w-]+)/$', TagListView.as_view(), name='tagged'),
        url(r'^(?P<category>[\w-]+)/(?P<slug>[\w-]+)/$', Detail.as_view(), name='detail'),
    

    I'm not sure that it good way, but it works. If you have any more prososals - please give me know