Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango KeyError {% if in %}
    primarykey
    data
    text
    <p>I'm teaching myself Django, and I'm trying to do a test thing such that a pre-existing user will get a page listing his or her "stuff," a new user will get a page informing him or her that they're not in the system, and a list of users can be generated. The problem is that I keep getting KeyErrors for any users not in the pre-existing users dictionary (it works fine if the user is in the dict). I'm not sure if the problem is in the way I've structured the relevant function in my views.py or in the way I'm using the templateTags, or what. Django's error page points to the context line of my views.py page, but I don't know if that's actually the problem.</p> <p>Any help would be greatly appreciated.</p> <p>My code:</p> <p>views.py:</p> <pre><code>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)) </code></pre> <p>samplate1.html:</p> <pre><code>&lt;html&gt; {% ifequal user "list" %} &lt;head&gt;&lt;title&gt;List of Users&lt;/title&gt;&lt;/head&gt; &lt;body&gt;&lt;h1&gt;List of users&lt;/h1&gt; &lt;ul&gt; {% for user in users %} &lt;li&gt;{{ user }}&lt;/li&gt; {% empty %} &lt;p&gt;No users listed!&lt;/p&gt; {% endfor %} &lt;/ul&gt; {% endifequal %} {% if user in users %} &lt;head&gt;&lt;title&gt;Greetings, {{ user }}&lt;/title&gt;&lt;/head&gt; &lt;body&gt; &lt;h1&gt;Hello&lt;/h1&gt; &lt;p&gt;Greetings, {{ user }}&lt;/p&gt; &lt;p&gt;The date is {{ date }}&lt;/p&gt; &lt;p&gt;The time is {{ time }}&lt;/p&gt; &lt;p&gt;Here is a list of your stuff:&lt;/p&gt; &lt;ul&gt; {% for item in user_stuff %} &lt;li&gt;{{ item }}&lt;/li&gt; {% empty %} &lt;p&gt;You don't have any stuff!&lt;/p&gt; {% endfor %} &lt;/ul&gt; {% else %} &lt;head&gt;&lt;title&gt;You're new here, huh?&lt;/title&gt;&lt;/head&gt; &lt;body&gt; &lt;h1&gt;Hello&lt;/h1&gt; &lt;p&gt;Your username is not in our database.&lt;/p&gt; &lt;p&gt;You should probably fix that.&lt;/p&gt; {% endif %} </code></pre> <p>and finally:</p> <p>urls.py:</p> <pre><code>... urlpatterns = ('', (r'^user/name/(.*)/$',hiUser), ) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload