Home > Net >  Images not appearing in Django template For Loop
Images not appearing in Django template For Loop

Time:11-05

HTML Inspector for first image element

Inspecting page in Chrome

I want to loop over a directory of static images in Django. The images are being looped over correctly, but something is wrong with my <img src /> syntax. I've tried many variations on {{ flag }} but can't get anything to work. Can anybody advise?

In settings.py I created the following STATIC_ROOT object:

STATIC_ROOT = '/Users/TheUnforecastedStorm/Desktop/Code_projects/Portfolio_Site/portfolio_site/entrance/static'

In views.py I joined this file path to my image directory and placed the list of images in the context dictionary. I then included this dictionary in my response:

import os
from django.conf import settings
from django.shortcuts import render

# Create your views here.
def index(request):
    # Create a dictionary
    context = {}

    # Join images directory to index.html view
    flags = os.listdir(os.path.join(settings.STATIC_ROOT, "entrance/images/"))  
    context['flags'] = flags
    
    # Return response
    return render(request, "entrance/index.html", context)

I then looped over these images in my template:

<!DOCTYPE html>
{% load static %}
<html>
    <head>
        <link rel="stylesheet" href="{% static 'entrance/entrance.css' %}">
        <script src="{% static 'entrance/entrance.js' %}" type="text/javascript"></script>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>

    <body>
        {% for flag in flags %}
            <img src="{{ flag }}" alt="problem" />
        {% endfor %}
    </body>
</html>

CodePudding user response:

@Mark1 Working off my comments from above, I haven't been able to find anything to confirm it but it seems like the {% static %} template tag can only take one extra argument to make a path, so here is something you can try.

In your view:

def index(request):
    # Create a dictionary
    context = {}

    # Join images directory to index.html view
    flags = os.listdir(os.path.join(settings.STATIC_ROOT, "entrance/images/"))

    # ADD IN THIS LINE HERE
    flags = ['entrance/images/' fl for fl in flags]


    context['flags'] = flags
    
    # Return response
    return render(request, "entrance/index.html", context)

The line I added in will add "entrance/images/" to the start of all the file names in the directory you are searching.

Then in your template

{% for flag in flags %}
   <img src="{% static flag %}" alt="problem" />
{% endfor %}

Let me know if this works.

  • Related