【问题标题】:Django Basics: Dynamic URL gives TypeErrorDjango 基础:动态 URL 给出 TypeError
【发布时间】:2013-06-26 08:26:37
【问题描述】:

我刚刚开始使用 Django,并且正在使用 djangobook.com。我尝试了动态 URL 示例,但它给了我一个 TypeError。你能看出什么问题吗?

views.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)

urls.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 个参数,一个给定”是什么意思.. 参数是 request 和 offset... 而 request 不是通过 get 内部传递的?

编辑:

这是base.html

<html>
<title> Test Project </title>
<body>
Hello {{ name }}
</body>
</html>

【问题讨论】:

  • 链接写成 localhost/name 等,因为 SO 不允许我输入 127.0

标签: python django dynamic-url


【解决方案1】:

感谢大家的帮助。我想到了。在这里发布以防其他人有同样的问题

https://docs.djangoproject.com/en/dev/topics/http/urls/ 的文档提到需要从 url 捕获的任何内容都需要放在括号中。 (我猜djangobook的pdf需要更新)

所以,在 urls.py 中,该行应该是

(r'^name/plus/(\d+)/$', nameOffset ),

而不是

(r'^name/plus/\d+/$', nameOffset ),

最后,它起作用了!

【讨论】:

    【解决方案2】:

    您应该使用正则表达式保存命名组,以便将 URL 的 \d+ 部分捕获到 offset 变量中:

    (r'^name/plus/(?P<offset>\d+)/$', nameOffset)
    

    另见documentation

    【讨论】:

    • 消除了错误 PAGE 但没有消除错误。如,页面应该是“Hello 123”,但它是“Hello”。我相信这叫做静默异常?
    • 你能显示你的base.html吗?另外,在视图中打印 offset 变量 - 你看到打印的值了吗?
    • 添加了 base.html。此外,不打印偏移量 -_-
    • 嗯,奇怪。打印的是什么?
    • Nothing... 它应该说“Hello 123”,但这个数字被忽略了。它只说“你好”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-21
    • 2016-07-29
    • 1970-01-01
    • 2011-01-07
    • 2019-06-20
    • 2015-04-15
    • 2016-07-03
    相关资源
    最近更新 更多