python - Django应用程序的<str :slug> and <slug:slug> in urls. py的区别

标签 python django django-models django-views django-templates

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

最佳答案

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路径转换仅作为 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/

相关文章:

python - 如何舍入 datetime64 值

django - 为简单的调查应用程序生成表单

javascript - jQuery:if语句来选择一个选项值

python - 类型错误 : on_delete must be callable

django - Django 测试用例中的 IntegrityError

python - Plotly:如何在单个绘图图中使用两种色标?

python - numpy 函数如何在内部对 pandas 对象进行操作?

python - 使用具有不同值的多个相同字符串解析 Python JSON

python - 使用 PIL 为 Django 网站旋转通过电子邮件上传的图像

Django 获取模型的所有相关值