简体   繁体   中英

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?

You're trying to access kwargs which are not even passed to the function. You should everywhere have

def func(self, *args, **kwargs):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM