How to add django template variable in <img src>? - python

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"/>

Related

Can't load static image in django when using a loop

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 }}">

How to access the image in django template? [duplicate]

I'm new in Django. I read a lot on documentation and on this site about my question. But I really can not understand what I should do to make this. Can someone show me with all steps please?
model.py:
class Post(models.Model):
title=models.CharField(max_lengt=50)
img=models.ImageField(upload_to = 'images')
template:
{% for post in posts %}
<h1> {{post.title}} </h1>
<img src="{{post.img}}">
{% endfor %}
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
If I access the admin page, how can I upload the image? In template I can't see image!
Sorry for my bad English. Help me please
In template, use:
{% for post in posts %}
<h1> {{post.title}} </h1>
<img src="{{ post.img.url }}">
{% endfor %}
You have to add {{ post.img.url }}.
Also, make sure that in urls.py, you have:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
It will Work.

"Could not load the image" from Django's media folder

I'm trying to display an image from a database (SQLite, Django2.7). These images are stored in root/media/pictures.
models.py
class News(models.Model):
news_id = models.AutoField(primary_key=True, editable=False)
news_img = models.FileField(upload_to="pictures/",validators=[FileExtensionValidator(allowed_extensions=['svg'])] )
urls.py
urlpatterns = [...]
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
I've try to insert the path in the var in the following methods:
template.html
{% for news_f in news_f%}
<div>
<img src="{{ media }}{{news_f.news_img}}">
</div>
{% endblock %}
and
{% for news_f in news_f%}
<div>
<img src="{{news_f.news_img.url}}">
</div>
{% endblock %}
When I inspect the element in the browser, I get the correct path to the file.
<img src="/media/pictures/file.svg">
But it isn't displayed in the HTML:
Could not load the image
That happens because django doesn't serve static files. Usually you use django along with some webserver like nginx and those servers are more reliable serving files.
Please check out django docs https://docs.djangoproject.com/en/2.2/howto/static-files/deployment/
Your configuration for media files is right, the problem is that Django doesn't serve SVG files with the right mime type by default, this answer explains how to make it work.

Static image url is returned without MEDIA_URL

i followed this tutorial about displaying profile pictures on website, i did everything correctly (i hope so) but instead of returning example.com/media/posters/pic1.jpg it returns example.com/pictures/pic1.jpg (real example)
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
views.py
def index(request):
movies = {'movies' : movie.objects.all()}
return render(request, 'index.html', movies)
models.py
class movie(models.Model):
poster = models.ImageField(upload_to='posters')
and html
{% for a in movies %}
<img src="{{ a.poster }}" alt="">
{% endfor %}
i added + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) to urls.py file
also, i had to use a.poster instead of poster.image.url, it just returned unknow, different django version i assume
You need {% get_media_prefix %}.

Django - Display ImageField

I've just started to use Django and I haven't found a lot of info on how to display an imageField, so I made this:
models.py:
class Car(models.Model):
name = models.CharField(max_length=255)
price = models.DecimalField(max_digits=5, decimal_places=2)
photo = models.ImageField(upload_to='site_media')
views.py:
def image(request):
carx = Car()
variables = RequestContext(request,{
'carx':carx
})
return render_to_response('image.html',variables)
image.html:
{% extends "base.html" %}
{% block content %}
<img src=carx />
{% endblock %}
I already save an image since terminal and I know is there, also if a do this in image.html:
{% block content %}
{{ carx }}
{% endblock %}
The output is: Car object
Can anyone tell me where is my error?
An ImageField contains a url attribute, which you can use in your templates to render the proper HTML.
{% block content %}
<img src="{{ carx.photo.url }}">
{% endblock %}
You can also make use of the Static URL in Settings.py. Make a directory for example "Uploads", in the Static directory of your app. Also change this in your model in models.py.
Use the following code:
<img src="{% static carx.photo.url %}" />
Thanks to all, i fix it in this way.
views.py
def image(request):
carx = Car.objects.all()
for mycar in carx:
MyCar = mycar.photo.url
variables = RequestContext(request,{
'carx':MyCar
})
return render_to_response('image.html',variables)
image.html
{% extends "base.html" %}
{% block content %}
<img src="{{ MEDIA_URL }}{{ carx }}"/>
{% endblock %}
settings.py
MEDIA_URL = '/Users/gcarranza/PycharmProjects/django_bookmarks/'
STATIC_URL = '/Users/gcarranza/PycharmProjects/django_bookmarks/site_media/'
STATICFILES_DIRS = (
'/Users/gcarranza/PycharmProjects/django_bookmarks/site_media',)
Now i know that carx.photo.url retrieve the absolute path of the file and its only matter to load as static file.

Categories

Resources