我在教自己的Django,我試圖做一個測試的事情,這樣一個預先存在的用戶將得到一個頁面列出他或她的「東西」,一個新用戶會得到一個通知他或她不在系統中的頁面,並且可以生成用戶列表。問題是我不斷獲取不在預先存在的用戶字典中的任何用戶的KeyErrors(如果用戶在字典中,它可以正常工作)。我不確定問題出在我在views.py中構建相關函數的方式,還是以我使用templateTags或其他方式的方式構建的。 Django的錯誤頁面指向了我的views.py頁面的上下文行,但我不知道這實際上是否是問題所在。Django KeyError {%if%}
任何幫助將不勝感激。
我的代碼:
views.py:
def hiUser(request,uname):
t = get_template("samplate1.html")
ds,ti = getTime()
user_stuff = {"sam":["a","b","c"],"kathy":["foo","bar"],"rob":[]}
c = Context({"date":ds,"time":ti,"user":uname,"user_stuff":user_stuff[uname],"users":user_stuff.keys()})
return HttpResponse(t.render(c))
samplate1.html:
<html>
{% ifequal user "list" %}
<head><title>List of Users</title></head>
<body><h1>List of users</h1>
<ul>
{% for user in users %}
<li>{{ user }}</li>
{% empty %}
<p>No users listed!</p>
{% endfor %}
</ul>
{% endifequal %}
{% if user in users %}
<head><title>Greetings, {{ user }}</title></head>
<body>
<h1>Hello</h1>
<p>Greetings, {{ user }}</p>
<p>The date is {{ date }}</p>
<p>The time is {{ time }}</p>
<p>Here is a list of your stuff:</p>
<ul>
{% for item in user_stuff %}
<li>{{ item }}</li>
{% empty %}
<p>You don't have any stuff!</p>
{% endfor %}
</ul>
{% else %}
<head><title>You're new here, huh?</title></head>
<body>
<h1>Hello</h1>
<p>Your username is not in our database.</p>
<p>You should probably fix that.</p>
{% endif %}
最後:
urls.py:
...
urlpatterns = ('',
(r'^user/name/(.*)/$',hiUser),
)
解決!謝謝。 – swizzard 2012-08-04 16:08:43