【问题标题】:Django pass multiple words through a URL confDjango 通过 URL conf 传递多个单词
【发布时间】:2015-04-20 20:26:45
【问题描述】:

使用 django,我想通过我的 URL conf 中的变量来命名我的项目。假设我的产品名称是“堆栈溢出”,我希望能够访问:

http://127.0.0.1:8000/product/stack+overflow/

但我得到的是“找不到页面”404 页面。当名称只是单词而不是多个单词时,它确实有效。

我的 urls.py

from django.conf.urls import patterns, url

urlpatterns = patterns('',
    url(r'^product/(?P<name>\w+)/$', 'crunch.views.product_by_name', name='preview_by_name'),
)

【问题讨论】:

    标签: python django django-urls


    【解决方案1】:

    您需要扩展您的正则表达式以匹配您希望在您的网址中允许的其他字符。

    在你的情况下允许字母数字字符和+,这应该工作:

    urlpatterns = patterns('',
        url(r'^product/(?P<name>[\w\+]+)/$', 'crunch.views.product_by_name', name='preview_by_name'),
    )
    

    【讨论】:

    • 唯一的问题是“+”不会像我想象的那样自动解码为空格字符。所以,我只是调用一个 str.replace("+", " ")
    • :) 我以为你是在尝试从字面上使用+urllib.unquote_plus() 可能是获得空间的另一种选择。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-03
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 2016-05-30
    • 2018-09-06
    • 1970-01-01
    相关资源
    最近更新 更多