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 }}">
Related
I've read through a few answers/articles at these links, but am still confused as all of them SEEM to be slightly different than what I'm after:
here
here
here
here
here
I am looking to make use of Django's ImageField function for uploading images from my admin page, to my portfolio/blog's app space. My folder structure looks like this:
Portfolio_Blog_Website
|---personal_portfolio_project
|---projects_app
|---migrations
|---static
|---img
|---templates
So I want to upload images to/display on the template from, the app > static > img folder.
Currently, I have STATIC_URL = 'static/' set, and I'm manually drag and dropping image files into that folder, and using models.FilePathField(path="/img") in the model, and displaying them (in a for loop) with <img src="{% static project.image %}">, which works. I want to switch to be able to upload images from the admin page, and then display them on the app's page like they're supposed to.
From what I've read, we have to define a MEDIA_ROOT and MEDIA_URL variable to use with models.ImageField(upload_to="img/"). The problem I see is that MEDIA_ROOT needs to be an ABSOLUTE path to the folder, which I COULD set as \\C:\Portfolio_Blog_Website\projects_app\static\img, however this isn't necessarily what I want because I'm specifically targeting the one specific app's path, but I don't want to upload images from other app's to that path also, so how can I make this work? I want each app to have its own static > img folders, and then from the admin page, I can upload to those specific app's directories, and then display them on each app's page.
In addition to my folder structure shown above, here's some other details that should help:
personal_portfolio_project > settings.py
STATIC_URL = 'static/'
MEDIA_URL = "/img/" # This doesn't work
MEDIA_ROOT = BASE_DIR # This doesn't work
projects_app > models.py
from django.db import models
# Create your models here.
# Portfolio project overview model
class Project(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
technology = models.CharField(max_length=20)
# image = models.FilePathField(path="/img") # works as /static/img, this works with STATIC_URL
image = models.ImageField(upload_to="img/") # This doesn't work
projects_app > project_index.html
{% extends "base.html" %}
{% load static %}
{% block page_content %}
<h1>Projects</h1>
<div class="row">
{% for project in projects %}
<div class="col-md-4">
<div class="card mb-2">
<img class="card-img-top" src="{% static project.image %}">
<div class="card-body">
<h5 class="card-title">{{ project.title }}</h5>
<p class="card-text">{{ project.description }}</p>
<a href="{% url 'project_detail' project.pk %}" class="btn btn-primary">
Read More
</a>
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
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 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"/>
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.
If I put my image in /media/ folder, it doesn't works. But if I put them in '/static/' folder it works.
{% extends 'base.html' %}
{% block contain %}
<h1>New Report</h1>
<form id="create" method="POST" action="" enctype="multipart/form-data">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Confirm">
</form>
{% for report in reports %}
<P> {{report.title}} </P> <br>
<img src="{{STATIC_URL}}<name of the image>" width='100px' height='100px'> =====> I can see the image
<img src="{{MEDIA_URL}} <name of the image>" width='100px' height='100px'> =====> I cant see the image
<img src="/static/<name of the image>" width='100px' height='100px'> =====> I cant see the image
<img src="/media/<name of the image>" width='100px' height='100px'> ====>>>> I cant see the image
{% endfor %}
{% endblock %}
Are you sure django testing server (or apache/nginx) knows about your media folder?
Try to add this to urls.py (in case you're using development server):
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
)
Putting images in your static folder will work, as the files in the static folder are served on the site. This is a potential solution and this discussion seems to suggest it's reasonable for some images. On my site the images in the media folder are located at /uploads/<name of the image>. This is what MEDIA_URL is set to. However I never explicitly call MEDIA_URL as all my images are tied into models so django handles that for me. My guess would be double check the name of the folder you're storing the images in and make sure you're looking at the right place. Second I would make sure that {{MEDIA_URL}} isn't undefined in the template.