python - Django 基础知识 : Dynamic URL gives TypeError

标签 python django dynamic-url

我刚刚开始使用 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/

相关文章:

python - 当目标函数有多个参数时如何使用 scipy.optimize minimize_scalar?

python - 运行 ubuntu vagrant server 不会在 debian 本地浏览器上显示任何内容

web-services - 具有动态 uri 的 spring 集成出站 web 服务网关并信任所有证书

php动态视频地址

Angular 6 - 带前缀的动态路由

python 记录到文件不起作用

python - Pycharm 剧照在重命名 .py 文件后显示旧名称。如何解决这个问题?

python - 如何在 Julia 中将多维数组解压为变量

javascript - 为什么 Django 中的 Google-Auth(Google Identity) 空白弹出窗口?

jquery - 如何修复 Django 中的错误 AttributeError : 'Country' object has no attribute 'City_set' .