Django URL页面参数和另一个参数

时间:2014-06-27 18:10:48

标签: django django-templates django-views django-urls

我该如何解决这个问题? 在我的模板中,我有这个:

<a href="{% url 'hp:category-filtered-page-blog' category=category page=page_obj.next_page_number %}">Next</a>

我想用另一个url参数进行分页。 所以我的CBV:

class CategoryFilteredBlogList(ListView):
    template_name = 'blog.html'
    context_object_name = 'posts'
    paginate_by = 1
    allow_empty = True

    def dispatch(self, *args, **kwargs):
        log_visitor(self.request, 'blog sort on category: {0}'.format(self.kwargs['category']))
        return super(CategoryFilteredBlogList, self).dispatch(*args, **kwargs)

    def get_queryset(self):
        print(self.kwargs['category'])
        self.category = get_object_or_404(Category, title=self.kwargs['category'])
        return Post.objects.filter(category__title__contains=self.category).order_by('-id')

    def get_context_data(self, **kwargs):
        context = super(CategoryFilteredBlogList, self).get_context_data(**kwargs)
        context['category'] = self.category
        return context

我的网址配置:

url(r'^blog/category/(?P<category>.+)$', CategoryFilteredBlogList.as_view(), name='category-filtered-blog'),
url(r'^blog/category/(?P<category>.+)/page/(?P<page>\w+)$', CategoryFilteredBlogList.as_view(), name='category-filtered-page-blog'),

它打印:'stuff / page / 2'但我只会'填充'。

1 个答案:

答案 0 :(得分:0)

问题是第一个url模式匹配包括斜杠本身在内的所有内容:

url(r'^blog/category/(?P<category>.+)$', CategoryFilteredBlogList.as_view(), name='category-filtered-blog'),

演示正在发生的事情:

>>> import re
>>> pattern = re.compile('^blog/category/(?P<category>.+)$')
>>> pattern.match('blog/category/stuff/page/2').group(1)
'stuff/page/2'

要解决此问题,只需删除第一个网址模式,然后让第二个网址模式捕获category

演示:

>>> pattern = re.compile('^blog/category/(?P<category>.+)/page/(?P<page>\w+)$')
>>> pattern.match('blog/category/stuff/page/2').group(1)
'stuff'

如果您希望该页面是可选的并允许blog/category/stuff等网址正常工作,您可以交换网址,以便首先检查该网页是否存在:

url(r'^blog/category/(?P<category>.+)/page/(?P<page>\w+)$', CategoryFilteredBlogList.as_view(), name='category-filtered-page-blog'),
url(r'^blog/category/(?P<category>.+)$', CategoryFilteredBlogList.as_view(), name='category-filtered-blog'),