Learning About Django Templates
I was working on a template last night to handle a generic view. I started by going into the console (managey.py shell) to poke around at the model I wanted to use. From that session, I copied the following snippet to use in the template.
project.projectimage_set.all()[0].image.url
I added this to the template and it looked like this.
{% for project in object_list %}
<div class="project">
<div class="project-image">
<img src="{{ project.projectimage_set.all()[0].image.url }}" alt="" />
</div>
<div class="project-info">
{{ project.name }}
{{ project.link|urlize }}
{{ project.description }}
</div>
</div>
{% endfor %}When running the template I received the error: “Could not parse the remainder: (0)”. I hadn’t seen this before and searched Google to get the answer. It didn’t look good on the first search. The answer was repeated in different results, originating from a Google group. The answer given (and I’m paraphrasing) was “Django templates don’t use Python code. You’re doing it wrong. Go write a template tag or custom method.” I read through the link a few times and couldn’t find the answer I wanted to hear. I figured this was common, and I thought a web framework for people with deadlines would not require me to write too much code to get to a property.
I went back to the documentation and looked around and still didn’t find anything that showed me how to access the properties further down on the related model so I went back to Google. This time I found an answer!
I’m not going to put on like I know what’s going on here. I can think about how somewhere underneath in the template language there’s an implementation of __getattr__, but I didn’t go and research it. It’s almost 0200 and sleep is calling. Because it was difficult for me to find, I thought I would just post this and maybe it would help the next guy stumble upon removing the () and [ ].
Here is the working code:
{% for project in object_list %}
<div class="project">
<div class="project-image">
<img src="{{ project.projectimage_set.all.0.image.url }}" alt="" />
</div>
<div class="project-info">
{{ project.name }}
{{ project.link|urlize }}
{{ project.description }}
</div>
</div>
{% endfor %}If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Thank you. Too bad the Django intro tutorial doesn’t mention that the template language is not really python. That makes things a bit confusing.