使用 re_path 处理 URL 参数中的空格

handle spaces in the URL parameter using re_path

我在 URL foo, bar 中传递了 2 个变量。变量 bar 有多个单词,它们之间有 spaces。在 foo 和 bar 的基础上渲染模板的内容。每当 bar 在单词之间有 space 时,我的 url 处理程序就会给出 404。

示例:localhost/post/foo/ba r/ 结果为 404

urls.py

urlpatterns = [
    re_path('post/<slug:foo>/<slug:bar>/', post),
]

views.py

def post(request, foo, bar):
    query = Blog.objects.all().filter(category=foo, title=bar)
    return render(request, 'blog/post.html',
                  {'blog': query, 'cat': foo, 'tit': bar})

post.html

{% for i in blog %}
    {{ i.content }}
{% endfor %}

您可以使用正则表达式允许空格和其他字符。

re_path(r'^post/(?P<foo>[\w|\W]+)/(?P<bar>[\w|\W]+)/$', post)