Django应用urls.py中<str:slug>和<slug:slug>的区别

The difference between <str:slug> and <slug:slug> in urls.py of Django application

  1. 为什么在某些情况下在urls.py中使用str:slug,而在其他情况下 slug:slug?有什么不同?哪个选项更好 使用?
  2. 我可以同时使用类别 slug 和文章 slug 吗 路线?

Why in some cases in urls.py is used str:slug, and in other cases slug:slug? What is the difference?

path converter [Django-doc]不同。实际上,<str:slug> 将接受与 <slug:slug> 将接受的字符串不同的一组字符串(在本例中为严格的超集)。

文档解释了将匹配的内容:

  • str - Matches any non-empty string, excluding the path separator, '/'. This is the default if a converter isn’t included in the expression.

  • slug - Matches any slug string consisting of ASCII letters or numbers, plus the hyphen and underscore characters. For example, building-your-1st-django-site.

str 将因此匹配任何非空字符串,因此它将接受 'foo''straße''foo bar',而 slug 路径convert 将仅作为 ASCII 字母和数字以及连字符和下划线的非空序列存在。

我们也可以在implementation of the StringConverter [GitHub] and the implementation of the SlugConverter [GitHub]中看到这个:

class StringConverter:
    regex = '[^/]+'

    def to_python(self, value):
        return value

    def to_url(self, value):
        return value

# ⋮

class SlugConverter(StringConverter):
    regex = '[-a-zA-Z0-9_]+'

因此 StringConverter 将使用 [^/]+ 正则表达式,而 slug 转换器将与 [-a-zA-Z0-9_]+ 正则表达式匹配。

通常,如果您使用 slug,最好使用 slug 路径转换器,因为这将 与非 slug 匹配,并且通常与 slug 匹配,不带字符串。

引入了 slug 来与漂亮的 URL 一起工作。 URL 其中 URL 参数包含 space 将被替换为 丑陋的 百分比编码,因此 foo%20bar,而 slug 将通常使用连字符,所以 foo-bar.

And can I use a category slug and then an article slug in one route?

当然你可以定义一个路径:

path('<strong><slug:category_slug></strong>/<strong><slug:article_slug></strong>/', some_view)

在这种情况下,some_view 将接受三个参数,因此:

def some_view(request<strong>, category_slug, article_slug</strong>):
    # …
    pass