[Answered ]-Django KeyError {% if in %}

1👍

Instead of user_stuff[uname] use user_stuff.get(uname). If the uname key doesn’t exist, the value will be None. Or you can use user_stuff.get(uname, []), which will make it an empty list if it doesn’t exist.

1👍

The problem is with your views.py – this part, specifically:

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

In order to solve this, you need to figure out what you’re going to do if a user isn’t in user_stuff. Are you going to raise a 404? Display an error? Fill in dummy content?

If you want to raise a 404, you could do it like this:

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

If you want to fill in dummy content, you could use dict.get, like this:

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

If you want to display an error page, you’ll want to modify the code sample that raises a 404.

Leave a comment