Search code examples
djangodjango-templatesdjango-viewsdjango-imagekit

django-imagekit - add a static link to a default avatar picture


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!


Solution

  • 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