Django url模式 - 字符串参数

rec*_*hie 42 python regex django

具有数字参数的Django url模式是:

url(r'^polls/(?P<poll_id>\d+)/$', 'polls.views.detail')
Run Code Online (Sandbox Code Playgroud)

如果我的poll_id不是数字而是字符串,那么正确的语法是什么?

小智 41

要在url中有一个字符串参数,你可以:url像这样:

url(r'^polls/(?P<string>[\w\-]+)/$','polls.views.detail')
Run Code Online (Sandbox Code Playgroud)

这甚至允许slug字符串传递,例如:node-js等字符串.


Ign*_*ams 34

取决于你关心的角色.就像文档说的那样,\w会给你一个字母数字字符或下划线.


And*_*röm 15

从Django 2.0开始,通过添加slug符号来更容易处理URL中的字符串参数,该符号与urls.py中的 int一样使用:

from django.urls import path

urlpatterns = [
    path('something/<slug:foo>', views.slug_test),
]
Run Code Online (Sandbox Code Playgroud)

在基于函数或基于类的视图中,您可以像处理任何其他参数一样处理它:

def slug_test(request, foo):
    return HttpResponse('Slug parameter is: ' + foo)
Run Code Online (Sandbox Code Playgroud)

  • 如果名称包含下划线,则 slug 类型将不起作用,因为 slug 希望它以连字符分隔。但如果这就是你想要的,这是一个很好的答案 (2认同)

小智 11

在较新版本的Django(例如2.1)中,您可以使用

path('polls/<str:poll_id>', views.polls_detail)
Run Code Online (Sandbox Code Playgroud)

如此处所示Django URL调度程序

def polls_detail(request,poll_id):
#process your request here
Run Code Online (Sandbox Code Playgroud)


Bin*_*ati 9

从 Django 2.0 开始,path已经引入。path在 url 中不使用 reg ex,因此它是旧版本的简化版本url

从 2.0 开始,您可以使用 path 代替,如下所示:

path('polls/<poll_id>', views.polls_detail)
Run Code Online (Sandbox Code Playgroud)

不需要明确指定字符串路径参数,因为路径参数的默认数据类型是字符串本身。

参考:https : //docs.djangoproject.com/en/2.0/releases/2.0/#whats-new-2-0