1

I'm using django-imagekit to get the image urls from a model called Avatar like this:

views.py

  my_results = SearchQuerySet().all()
  try:
    user_avatar = Avatar.objects.filter(user__in=[x.object.user_id for x in my_results])
  except Avatar.DoesNotExist:
    err='avatar does not exist'

template.html

{% for result in my_results %}

<img src="{% for avatar in user_avatar %}
{% if result.object.user.id = avatar.user.id %}
{{ avatar.thumbnail_image.url }}
{% endif %}
{% endfor %}" 
width="75" height="75" border="0">

{{ result.object.time|date:"M d y" }}

{% endfor %}

Using the above code currently I'm able to see the picture urls for the users that loaded a picture for their avatars.

But there is a case where users didn't load any pictures for their avatars so I need to add a static url to a default avatar picture but I don't know how.

Is it possible to add a static link using the template tags in the template.html and how? If not I'm open to any solution. Thank you!

Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162
avatar
  • 12,087
  • 17
  • 66
  • 82

1 Answers1

3

Why you are looping over user_avatar? You have a guarantee that you have only one result?

In any case i would change a bit your code.

{% load staticfiles %}

{% for result in my_results %}
  {% if avatar %}
    {% for avatar in user_avatar %}
      {% if result.object.user.id = avatar.user.id %}
        <img src="{{ avatar.thumbnail_image.url }}" width="75" height="75" border="0" />
    {% endfor %}
  {% else %}
      <img src="{% static "images/hi.jpg" %}" width="75" height="75" border="0" />
  {% endif %}

{{ result.object.time|date:"M d y" }}

{% endfor %}

Please have look on https://docs.djangoproject.com/en/dev/howto/static-files/#with-a-template-tag

Or if you handle your static files in a different way, you only have to put your static link to the placeholder image

EDIT

views.py

my_results = SearchQuerySet().all()
try:
    user_avatar = Avatar.objects.filter(user__in=[x.object.user_id for x in my_results])
except Avatar.DoesNotExist:
    user_avatar = None
Ivan Pereira
  • 2,149
  • 3
  • 24
  • 32
  • I tried your solution but for some reason I'm getting both urls at the same time. I'm getting the link to the existing avatars and right by it the url to the default avatar. Where is no avatar in the database I'm getting two urls to the default avatar. To answer your question, yes I must guarantee that there is only one avatar per record/result. – avatar Nov 05 '11 at 22:26
  • I have changed your template.html and views.py, you need to check in your views.py if avatar exists for that user. If don't work please post your complete view because i'm making some assumptions here. – Ivan Pereira Nov 06 '11 at 00:52