- 为什么在某些情况下 urls.py 中使用 str:slug,而在其他情况下 蛞蝓:蛞蝓?有什么不同?哪个选项更好 使用?
- 我可以同时使用类别别名和文章别名吗 路线?
最佳答案
Why in some cases in urls.py is used
str:slug
, and in other casesslug: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
路径转换仅作为 ASCII 字母、数字、连字符和下划线的非空序列存在。
我们也可以在 implementation of the StringConverter
[GitHub] 中看到这一点和 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_]+
匹配正则表达式。
通常,如果您使用 slugs,最好使用 slug 路径转换器,因为这不会与非 slugs 匹配,并且通常与 slugs 匹配,而不是与字符串匹配。
引入了一个 slug 来处理漂亮的 URL。 URL 参数包含空格的 URL 将被替换为丑百分比编码,因此 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
关于python - Django应用程序的<str :slug> and <slug:slug> in urls. py的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68945473/