【问题标题】:Page not found when passing parameters via URL in Django在 Django 中通过 URL 传递参数时找不到页面
【发布时间】:2012-05-16 07:16:05
【问题描述】:

我怀疑这可能与我设置正则表达式样式的方式有关,因为当我尝试转到时会得到以下输出:例如 http://127.0.0.1:8000/recipes/search/fish/...

使用 gfp.urls 中定义的 URLconf,Django 按以下顺序尝试了这些 URL 模式:

^recipes/$
^recipes/category/(?P<category>\d+)/$
^recipes/search/(?P<term>\d+)/$
^recipes/view/(?P<slug>\d+)/$
^admin/

当前 URL,recipes/search/fish/,与其中任何一个都不匹配。

这里是我的 URLconf 供参考

urlpatterns = patterns('',
url(r'^recipes/', 'main.views.recipes_all'),
url(r'^recipes/category/(?P<category>\d+)/$', 'main.views.recipes_category'),
url(r'^recipes/search/(?P<term>\d+)/$', 'main.views.recipes_search'),  
url(r'^recipes/view/(?P<slug>\d+)/$', 'main.views.recipes_view'),

以下是我目前尝试使用的视图供参考

def recipes_all(request):
    return HttpResponse("this is all the recipes")

def recipes_category(request, category):
    return HttpResponse("this is the recipes category % s" % (category))

def recipes_search(request, term):
    return HttpResponse("you are searching % s in the recipes" % (term))

def recipes_view(request, slug):
    return HttpResponse("you are viewing the recipe % s" % (slug))

我怀疑这是我的正则表达式,谁能解释一下它有什么问题?我已经看到 /w(?) 用于某些 url 正则表达式,但它没有在 Django tuorial 中使用:

https://docs.djangoproject.com/en/1.4/intro/tutorial03/

【问题讨论】:

    标签: python regex django


    【解决方案1】:

    '^recipes/search/(?P&lt;term&gt;\d+)/$' 匹配 /recipes/search/123456/ 而'^recipes/search/(?P&lt;term&gt;[-\w]+)/$' 可能是您需要的。 (用连字符更新)

    查看 Python re 文档以了解 '\d'、'\w' 和其他内容的含义。

    【讨论】:

    • 也谢谢!行得通,是 \d 数字和 \w 字符吗?我怎么能允许连字符这一行,因为它看起来像 \w 不会接受这个?我猜 \d 也没有?
    • \w 通常是任何字母数字字符和下划线
    • 所以我应该将我的 slug 存储为带有下划线的名称?由于 django 中的 slugify 字段使用 - - - 破折号
    • slug 中包含连字符是可以的。只需使用我提供的正则表达式[-\w]+
    【解决方案2】:

    recipe/search 的 urlpattern 只允许数字 (\d) 用于搜索词。改成\w,应该就好了。

    【讨论】:

    • 谢谢! \d numeric 和 \w char 还是 varchar 也是如此?
    猜你喜欢
    • 2015-12-04
    • 2013-09-26
    • 2011-10-07
    • 1970-01-01
    • 2018-09-06
    • 1970-01-01
    • 2016-02-02
    • 1970-01-01
    • 2022-01-25
    相关资源
    最近更新 更多