template IndexError (list index out of range)

189 views
Skip to first unread message

Jonathan Lukens

unread,
Apr 12, 2008, 9:28:17 AM4/12/08
to Django users
I started getting an IndexError on a page today that has worked fine
in the past. The uses a wrapped object_list generic view to render a
template with the following loop:

{% for baby in object_list %}
{% if baby.photo %}
<p><img src="{{ baby.photo.get_thumbnail_url }}" /></p>
{% endif %}
<p>
<a href="{{ baby.get_absolute_url }}">
{{ baby.display_name }} {{ baby.last_name }}...</a>
</p>
<p>... is {{ baby.age }}</p>
{% endfor %}

I tried generating the same list in shell and was able to run a for
loop on it without any trouble. I compared the model and the template
with the last commit to svn (which worked) and nothing was different
except a couple of custom methods on the model being looped over. I
commented out those methods and restarted the server but got the same
error. Here is the traceback:

File "/usr/lib/python2.5/site-packages/django/template/debug.py" in
render_node
71. result = node.render(context)
File "/usr/lib/python2.5/site-packages/django/template/defaulttags.py"
in render
149. nodelist.append(node.render(context))
File "/usr/lib/python2.5/site-packages/django/template/defaulttags.py"
in render
239. value = bool_expr.resolve(context, True)
File "/usr/lib/python2.5/site-packages/django/template/__init__.py" in
resolve
518. obj = self.var.resolve(context)
File "/usr/lib/python2.5/site-packages/django/template/__init__.py" in
resolve
659. value = self._resolve_lookup(context)
File "/usr/lib/python2.5/site-packages/django/template/__init__.py" in
_resolve_lookup
694. current = current()
File "/home/jonathan/workspace/datababy/src/datababy/child/models.py"
in photo
96. return self.photo_set.all()[0]
File "/usr/lib/python2.5/site-packages/django/db/models/query.py" in
__getitem__
157. return list(self._clone(_offset=k,
_limit=1))[0]

Exception Type: IndexError at /users/jonathan/
Exception Value: list index out of range

Karen Tracey

unread,
Apr 12, 2008, 11:12:00 AM4/12/08
to django...@googlegroups.com

 
This is the line of code causing the problem:

File "/home/jonathan/workspace/datababy/src/datababy/child/models.py"
in photo
 96.         return self.photo_set.all()[0]

It is assuming there is at least one photo in the set, but apparently there are none.  This would seem to be coming from the {% if baby.photo %} line in your template.  Your code needs to handle the case where self.photo_set.all() is empty.

Karen

 

Jonathan Lukens

unread,
Apr 12, 2008, 12:56:34 PM4/12/08
to Django users
Of course. Thank you. I'm nearly braindead from doing taxes.

On Apr 12, 11:12 am, "Karen Tracey" <kmtra...@gmail.com> wrote:
> On Sat, Apr 12, 2008 at 9:28 AM, Jonathan Lukens <jonathan.luk...@gmail.com>
Reply all
Reply to author
Forward
0 new messages