跟着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})
<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__是变量,不应该加单引号。
改过来就对了:
心得:
只是看书,是不行的。只有亲手打上一遍,才能记住。
即使按照教程打,还是错。