Django KeyError {%if in in}

时间:2012-08-03 21:27:37

标签: python django

我正在教自己Django,我正在尝试做一个测试,以便预先存在的用户将获得一个列出他或她的“东西”的页面,新用户将得到一个页面通知他或她它们不在系统中,可以生成用户列表。问题是我一直在为不在预先存在的用户词典中的任何用户获取KeyErrors(如果用户在dict中,它可以正常工作)。我不确定问题是否与我在views.py中构建相关函数的方式或我使用templateTags的方式有关。 Django的错误页面指向我的views.py页面的上下文行,但我不知道这是否真的是问题。

非常感谢任何帮助。

我的代码:

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),
)

2 个答案:

答案 0 :(得分:1)

问题在于你的views.py - 这一部分,具体来说:

c = Context({"date":ds,"time":ti,"user":uname,"user_stuff":user_stuff[uname],"users":user_stuff.keys()})

为了解决这个问题,如果用户不在user_stuff,你需要弄清楚你要做什么。你要筹集404吗?显示错误?填写虚拟内容?

如果你想筹集404,你可以这样做:

from django.http import Http404

def hiUser(request,uname):
    t = get_template("samplate1.html")
    ds,ti = getTime()
    user_stuff = {"sam":["a","b","c"],"kathy":["foo","bar"],"rob":[]}

    if uname not in user_stuff:
        raise Http404

    c = Context({"date":ds,"time":ti,"user":uname,"user_stuff":user_stuff[uname],"users":user_stuff.keys()})
    return HttpResponse(t.render(c))

如果您想填写虚拟内容,可以使用dict.get,如下所示:

def hiUser(request,uname):
    t = get_template("samplate1.html")
    ds,ti = getTime()
    user_stuff = {"sam":["a","b","c"],"kathy":["foo","bar"],"rob":[]}

    stuff_for_user = user_stuff.get(uaname, [])
    c = Context({"date":ds,"time":ti,"user":uname,"user_stuff":stuff_for_user,"users":user_stuff.keys()})

    return HttpResponse(t.render(c))

如果要显示错误页面,则需要修改引发404的代码示例。

答案 1 :(得分:1)

而不是user_stuff[uname]使用user_stuff.get(uname)。如果uname密钥不存在,则值为None。或者您可以使用user_stuff.get(uname, []),如果它不存在,将使其成为空列表。