Solution 1 :

I’m not clear about what you’re looking for, but from

create image tags for every file in a directory located in static

I’m assuming that you’re looking to load image using the {% static %} tag:

{% load static %}
...
<img src="{% static 'path_to_image' %}" alt="img1.jpg" height="100px" width="100px">
<!-- Watch out the single and double quotes -->

Do remember to include this in your settings.py:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'), // or wherever you put your static files
]

I think it’s now automatic, but check your INSTALLED_APPS:

INSTALLED_APPS = [
    ...
    'django.contrib.staticfiles',
]

Compared to hard-coded paths like C:/foo/baz/bar/, it’s better to load static tags because it always works on different platforms as every operating system has its own way to handle files, which I hope answers your question.

Problem :

I am trying to create image tags for every file in a directory located in static in my Django project. What is the best way to do this? I suppose I could write pure python with os.listdir and just use strings to concatenate the image tags together using the filenames, but I’m sure there’s a better way using Django’s HTML formatting. Haven’t been able to figure it out.

Example: In a folder there is img1.jpg and img2.jpg.

How can I produce:

<img src="img1.jpg" alt="img1.jpg" height="100px" width="100px">
<br>
<img src="img2.jpg" alt="img2.jpg" height="100px" width="100px">
<br>

Comments

Comment posted by R.F.

Thank you, that is helpful, but I’m looking to do this but for every file in a directory (e.g.

Comment posted by crimsonpython24

I’m unsure about what you mean by

Comment posted by R.F.

The pseudo code would be:

Comment posted by crimsonpython24

Try this:

Comment posted by R.F.

Ok, cool thanks, that makes sense. Can you share how I would iterate through in the HTML though? Otherwise I’ll eventually figure it out with the helpful info you’ve shared on view capability. Appreciate your help!

By