初学pyton on django犯的低级错误:need more than 1 value to unpack

跟着djbook学习,它说,没有自己真正写一个模板,就不能真正成长。

于是早上写了一个简单的view和模板,刚开始学。

View文件,是照着教程写的。

def book_list(request):
    db=MySQLdb.connect(user='root',db='db1',passwd='password',host='127.0.0.1')
    cursor=db.cursor()
    cursor.execute('select * from book order by id')
    books=[row[1] for row in cursor.fetchall()]
    book = books[2]
    #assert()
    db.close()
    return render_to_response("book_list.html",{'book':book,"books":books})

注:return render_to_response的第2个参数是个字典,多个上下文(变量)就使用逗号分割,放在一个花括号里。
模板文件

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>book list</title>
</head>

<body>
<ul>
<li>{{ book }}</li>
{% for book1 in books %}
<li>{{ book1 }} </li>
{% endfor %}
</ul>
</body>
</html>

总是报错误

ValueError at /book/
need more than 1 value to unpack


如果按照创建模板,创建上下文就行。



卡住了,加入assert跟踪,看数值都对啊。

后来看老外也有同样的错误,他的seeting.py是

TEMPLATE_LOADERS = (
    '/Users/some_user_name/Sites/djcode/dev2/template',
)

回答者说:

You've set the wrong thing in settings.py. TEMPLATE_LOADERS is for Python code that finds and loads templates. You want to put your directory into TEMPLATE_DIRS.


敲打和他犯了同样的错误,把模板路径放错了。

应该是

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    #os.path.join(os.path.dirname('__file__'),'template/').replace('\\','/'),
    'i:/mysite/mysite/template',
)

注:__file__是变量,不应该加单引号。


是TEMPLATE_DIRS,而不是TEMPLATE_LOADERS。

改过来就对了:

心得:

只是看书,是不行的。只有亲手打上一遍,才能记住。

即使按照教程打,还是错。




评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

容沁风

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值