2

I am trying to render a list of lists zipped with zip().

list_of_list = zip(location,rating,images)

I want to render this list_of_list to template and want to show only the first image of each location.

my location and image models are these:

class Location(models.Model):
  locationname = models.CharField

class Image(models.Model):
  of_location = ForeignKey(Location,related_name="locs_image")
  img = models.ImageField(upload_to=".",default='')

here is the zipped list. How can I access only the first image of each location in template?

enter image description here

3
  • Just curious, why are you zipping actually? Why not use relationships? Commented Mar 29, 2013 at 13:46
  • @Bibhas, you mean: all_locations = Location.objects.all() and in template {% for loc in all_locations %} {% for img in loc.locs_image.all %}{{img.img.name}} {% endfor %} {% endfor %} ? Commented Mar 30, 2013 at 2:37
  • 1
    Yes. Why not that? And if you want just one item, you can use slice tag in templates. Commented Mar 30, 2013 at 7:06

3 Answers 3

5

Pass the list_of_lists to the RequestContext. Then you can reference the first index of the images list in your template:

{% for location, rating, images in list_of_lists %}

...
<img>{{ images.0 }}</img>
...

{% endfor %}

How to render a context

Sign up to request clarification or add additional context in comments.

1 Comment

Can you show your render-function and the part of your template that you're targeting?
1

I think you should have a look at django-multiforloop.

Comments

0

You can handle list elements in your template also based on their type (with Django 1.11 ).

So in case you have the view you describe:

# view.py
# ...
list_of_lists = zip(location,rating,images)
context['list_of_lists'] = list_of_lists
# ...

All you need to do is create a tag to determine the type of your elements in the template:

# tags.py
from django import template
register = template.Library()
@register.filter
def get_type(value):
    return type(value).__name__

Then you can detect the content type of a list element and only display the first element if the list element is a list itself:

{% load tags %}
{# ...other things #}
<thead>
  <tr>
    <th>locationname</th>
    <th>rating</th>
    <th>images</th>
  </tr>
</thead>
<tbody>
  <tr>
    {% for a_list in list_of_lists %}
    {% for an_el in a_list %}
    <td>
        {# if it is a list only take the first element #}
        {% if an_el|get_type == 'list' %}
        {{ an_el.0 }}
        {% else %}
        {{ an_el }}
        {% endif %}
    </td>
    {% endfor %}
  </tr>
  % endfor %}
</tbody>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.