【问题标题】:handle spaces in the URL parameter using re_path使用 re_path 处理 URL 参数中的空格
【发布时间】:2018-06-11 09:20:55
【问题描述】:

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

示例:localhost/post/foo/bar/ 导致 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 %}

【问题讨论】:

  • 您可以尝试在query 之前记录foobar 吗?
  • 我不明白,如何登录? @Umair
  • 尝试print(foo) print(bar)并检查控制台中的输出[假设您使用的是python3]
  • 我已经在我的实际代码中这样做了,这只是我发布的一个精简版本。我的数据库模型是这样设置的,bar 将在它们之间包含多个单词和空格
  • 那里打印的是什么?

标签: django url-routing


【解决方案1】:

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

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

【讨论】:

  • 我很高兴它有帮助。
猜你喜欢
  • 1970-01-01
  • 2021-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-19
  • 2011-03-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多