为什么django url中没有捕获变量作为字符串传递给视图?

时间:2016-06-25 17:46:10

标签: django python-3.x django-views url-pattern

我试图在我的urls.py文件中捕获url中的变量,然后将其传递给我的视图文件中的函数,我想将其用作字符串:

# urls.py
from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^posts/(?P<title>)', views.blog_ronn_post, name='blog_ronn_post'),
]

# views.py
from django.http import HttpResponse

def blog_ronn_post(request, title):
    html = "<html><body>This is the page for the blog titled: {s} </body></html>".format(title)
    return HttpResponse(html)

然而,这不起作用。在我的开发浏览器中,html显示,但在最终冒号后没有显示任何内容。我不认为我的Python 3语法存在问题,就好像我尝试使用括号格式的字符串,例如:

 html = "<html><body>This is the page for the blog titled: {s} </body></html>".format('Title 1')

它有效,显示“......标题:标题1”。那么为什么它没有通过我的标题字符串?我理解标题作为字符串从url传递到视图,所以应该没有问题。如果我犯了一个明显的错误,django的新手很抱歉。

1 个答案:

答案 0 :(得分:3)

因为你还没有给它任何东西来匹配。

r'^posts/(?P<title>\w+)$'