I try to display all images from a directory that is in the project.
In the views.py
def showimages(request):
path='C:\\Users\Peter\PycharmProjects\displayimages\displayimages\display\static'
img_list = os.listdir(path)
return render(request, 'displayphotos.html', {'images':img_list})
In the html file
{% for image in images %}
<p>{{image}}</p>
<img src="{% static '{{image}}' %}">
{% endfor %}
But the display is
<p>DSC_5390.jpg</p>
<img src="/static/%7B%7Bimage%7D%7D">
<p>DSC_5392.jpg</p>
<img src="/static/%7B%7Bimage%7D%7D">
If I print them in paragraph tag, all file names are correct, but all wrong in img tag. How can I fix it?
you have an easy issue, just write
<img src="{% static {{image}} %}">
insead of
<img src="{% static '{{image}}' %}">
remove the simple quotes
if you have the image inside you static folder than you first need to load the static folder in setting file.
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
and than just load the image with the correct path in your template. if you have a folder for your images than
<img src="{% static 'images/grad-hat.png' %}">
else the image name
<img src="{% static 'grad-hat.png' %}">
Related
I have six images name as 1.jpg to 6.jpg of each side of dice and I want to display image defined by a random number I generate in runtime.
How can I make dynamic path including this random number? I tried some ways but getting 404 image not found only.
settings.py
STATIC_URL = '/static/'
Folder with images:
D:\programs\Django_projects\src\dice\random_dice\static\images
Dice is my project name and random_dice is my app name.
I already tried this:
<img class="myImage" src='{% static "images/{{ number }}.jpg"%}' alt="can not load the image">
and
<img class="myImage" style="background-image:url('{{ STATIC_URL }} images/{{ number }}.jpg')" alt="can not load the image">
Also tried before the rendering page to make custom name and put in dict but still not working
view.py
def home(request):
X = random.randrange(1, 6)
result = {
"number": X,
"myImage": str(X) + '.jpg'
}
return rander(request, 'home.html', result)
In that condition ...
<img class="myImage" src='{% static "images/{{ myImage }}"%}' alt="can not load the image">
And
<img class="myImage" style="background-image:url('{{ STATIC_URL }} images/{{ myImage }}')" alt="can not load the image">
Should I move image folder to else position or change STATIC_URL or the syntax is wronge? I have no idea please help.
One of possible solutions:
<img class="myImage" src='{% static "images" %}{{ myImage }}' />
static "images" will prepend "images" with STATIC_URL, myImage was taken outside of {% %} and now double curly braces work fine.
I am unable to upload
style="background-image:url(images/home_slider.jpg)"
file in django. I have made two changes in settings .That is as follows:
STATIC_URL = '/static/'
STATICFILES_DIRS=[ os.path.join(BASE_DIR,'static')]
STATIC_ROOT=os.path.join(BASE_DIR,'assets')
I also tried this
style=" {% static'background-image:url(images/home_slider.jpg)' %}"
But unable to remove error.
Adding more details:
load static files in your template
{% load staticfiles %}
Usage of img tag:
<img src="{% static 'images/image.jpg'%}" alt="">
In your case:
style="background-image: url('{% static "images/image.jpg" %}');"
Add static only where you use the path of the file. So:
style="background-image: url({% static 'images/home_slider.jpg' %});"
Don't forget to place {% load static %} at the top.
I cant get an image to load in django when i use a for loop, the image will load if i specify the path for each file.
Works:
when I try to use a loop it won't load the images.
view.py:
operators = []
directory =
os.path.join(os.path.join(os.path.join(os.path.join(settings.BASE_DIR)
,'static'),'images'),'operators')
for file in os.listdir(directory):
if file.endswith(".png") or file.endswith(".jpg"):
operators.append(file)
then i try to return image using context.
html file:
{% if operators %}
There are {{ operators|length }} records:
{% for operator in operators %}
<div class="media">
<img src="{{operator}}" class="align-self-center mr-3" alt="...">
</div>
{{operator}}
{% endfor %}
{% else %}
There are no records in the system
{% endif %}
It would be amazing if someone had an idea on how to fix my code.
settings.py:
STATIC_URL = '/static/'
# Pointing django to the static file location.
STATICFILES_DIRS = (
os.path.join(BASE_DIR,'static'),
)
The answer may vary depending on which version of Django you're using.
For Django 3.0, the following should work
# settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
'static',
]
Then inside templates-
{% load static %}
<img src="{% static '{{ operator.url }}' %}">
I'm guessing the images may appear instead with the following-
<img src="{{ operator.url }}">
I have a Django project with a static/img folder I want to get this image loaded but since it's in a variable and static points to my static folder, not static/img I'm not sure how to get it in. I tried f'img/{project.image}'
I'm iterating through projects so
project.image is set to equal "some_image_for_this_project.jpg" in my database
<img class="card-img-top" src="{% static project.image %}">
Probably not the most elegant solution, but this is how it should work:
<img src="{% static 'images/' %}{{ project.image }}>
Maybe it will help
1.) Youre template.html
{% load static %}
{% static 'img/name_img.jpg' %}
*This solution works for the directory structure
app
/__pycache__
/migrations
/templates
/static/img/[YOURE_FILES...]
__init__.py
[...]
I have a Photo model with two fields:
title = models.CharField()
path = models.CharField()
When I adding the new photo in admin panel, the path is equals to /images/image_ex.jpg This is my view file:
def gallery(request):
photos = Photo.objects.all()
return render(request, 'gallery.html', {'photos': photos})
This is the tag in gallery.html:
{% loadstaticfiles %}
<img src="{%static '{{photo.path}}'%}"/>
The problem is that the photo does not render and if I look in the code of the page, the src is equals to something like that:
src="static/%7B%7B%20photo.path%20%7D%7D"
What is the problem? How can I use template variables in src?
P.S. The images folder exists in static folder, the image exists too. I added static directory to settings.py. Also if I change src to a normal one, like
<img src="{static 'images/image_ex.png'%}">
The photo renders normally.
You here pass '{{photo.path}}' as a string to {% static ... %}, hence it will simply prepend the static URL root to this string.
If you want to use the content of photo.path, you can use:
<img src="{% static photo.path %}"/>
So {% static ... %} accepts variables as parameters, and will take the content of the path attribute of the photo variable. (of course given that variable is passed, or is a variable you generate with {% for ... %} loops, etc.
Uses a for tag
{% for p in photos %}
<img src="{% static '{{ p.path }}' %}"/>
{% endfor %}
Better uses Imagefield as field in your model
In your settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
Create a folder named “media” in your project (at the same level that your apps)
In your urls.py (main)
from . import views, settings
from django.contrib.staticfiles.urls import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
In your models.py
Replace the CharField with Imagefield
image = models.ImageField(upload_to="my_folder_name")
Like this:
class Photo(models.Model):
title = models.CharField()
image = models.ImageField(upload_to="my_folder_name"))
In your views.py
def gallery(request):
photos = Photo.objects.all()
return render(request, 'gallery.html', {'photos': photos})
In your templates
{% for p in photos %}
<img src="{{ p.photo.url }}"/>
{% endfor %}
Do it like this:
<img src="{static 'images/'%}{{image_ex.png}}">
Use it after the static tag scope ends.
For Template
{% for image in all_image %}
<img src="{{ image.image.url }}"/>
{% endfor %}
Solved: load image dynamically in survey.html
"survey.toolsTechnology" is a dynamic variable, every time the
variable changes, the image also changes based on it.
<img src="{% static 'images/'%}{{survey.toolsTechnology}}.png"/>