我刚刚开始使用 Django,并且正在使用 djangobook.com。我尝试了动态 URL 示例,但它给了我一个类型错误。你能看出哪里出了问题吗?
View .py
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
import datetime
def nameOffset(request, offset):
print "in nameOffset"
t = get_template('base.html')
html = t.render(Context({'name':offset}))
return HttpResponse(html)
url.py
from django.conf.urls import patterns, include, url
from MemberInterface.views import getName, nameOffset
urlpatterns = patterns('',
(r'^name/$', getName ),
(r'^name/plus/\d+/$', nameOffset ),
)
/localhost/name/一切都很好
但是当我转到/localhost/name/plus/1/时,我得到
TypeError at /name/plus/1/
nameOffset() takes exactly 2 arguments (1 given)
Request Method: GET Request URL: /localhost/name/plus/1/
Django Version: 1.5.1 Exception Type: TypeError Exception Value:
nameOffset() takes exactly 2 arguments (1 given)
“2 个参数,一个给定”是什么意思……参数是请求和偏移量……并且请求不是通过 get 内部传递的吗?
编辑:
这是base.html
<html>
<title> Test Project </title>
<body>
Hello {{ name }}
</body>
</html>
最佳答案
谢谢大家的帮助。我想到了。在此发布以防其他人遇到同样的问题
文档位于https://docs.djangoproject.com/en/dev/topics/http/urls/提到需要从 url 捕获的任何内容都需要放在括号中。 (我猜 djangobook 的 pdf 需要更新)
因此,在 urls.py 中,该行应该是
(r'^name/plus/(\d+)/$', nameOffset ),
而不是
(r'^name/plus/\d+/$', nameOffset ),
最后,它起作用了!
关于python - Django 基础知识 : Dynamic URL gives TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17315077/