【问题标题】:Regex paths with Django. a list of items via clean URLsDjango 的正则表达式路径。通过干净的 URL 列出的项目列表
【发布时间】:2021-10-02 15:02:46
【问题描述】:

我需要像/catalog/catalog_slug/tag_slug1/tag_slug2/tag_slug3这样的网址

re_path(r'^catalog/(?P<catalog_slug>\w+)/(?P<tag_slugs>(?:\w+/)+)', ...)

我阅读了如何做多个 tag_slugs,但是当我将它与另一个模型(目录) This stackoverflow answer[] 的单个 slug 混合时,我得到了:

TypeError: get() got multiple values for argument 'catalog_slug'

我的看法


class CategorySeoTagsView(APIView):
    def get(self, catalog_slug, tag_slugs):
        pass

【问题讨论】:

  • @thebjorn,同样的错误
  • @thebjorn 我更新了回溯。我没有更多信息,只是我需要 /catalog/somecatalogslug/tagslug1/tagslug2/tagslug3/ 之类的东西来按标签过滤

标签: python django regex


【解决方案1】:

一种方法是编写一个包罗万象的正则表达式,然后在您的视图中对其进行后处理:

from django import http

def print_tags(request, catalog_slug, tag_slugs):
    print(catalog_slug)
    print(tag_slugs)
    print(tag_slugs.split('/'))
    return http.HttpResponse("OK")


urlpatterns = [
    url(r'^catalog/(?P<catalog_slug>\w+)/(?P<tag_slugs>[/\w]+)/$', print_tags),
    ...
]

然后将打印 url http://localhost:8000/catalog/foo/bar/baz/

foo
bar/baz
['bar', 'baz']

但你也可以使用get参数:

def print_tags2(request, catalog_slug):
    print(catalog_slug)
    print(request.GET.getlist('tag_slugs'))
    return http.HttpResponse("OK")

urlpatterns = [
    url(r'^catalog/(?P<catalog_slug>\w+)/$', print_tags2),
    ...
]

那么你需要在 URL 中传递参数,例如:

http://nho:8752/catalog/foo/?tag_slugs=bar&tag_slugs=baz

【讨论】:

    猜你喜欢
    • 2012-12-24
    • 2020-01-18
    • 2011-01-22
    • 1970-01-01
    • 2016-01-10
    • 2018-11-27
    • 2012-08-14
    • 1970-01-01
    • 2023-03-24
    相关资源
    最近更新 更多