Templates do not show image. Django - python

Here is what i tried to do:
in my settings.py:
TEMPLATES = [
...
'OPTIONS': {
'context_processors': [
...
'django.template.context_processors.media',
],
},
},
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'img')
MEDIA_URL = '/img/'
i have also added this in my main urls.py:
static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And here's the code in my template:
<img
src="{{ product.image.url }}"
alt="Not available"
height="188px"
style="margin: 10px 0"
width="188px"
/>
Edit ...
I solved my problem :)
This is what is did
src="{{ MEDIA_URL }}{{ product.image.url }}"
i added {{ MEDIA_URL }} in src of my <img> tag.

In my project, I have added main urlpatterns as :
urlpatterns = urlpatterns + \
static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And it working fine.

Try using this for your static file resource
STATIC_URL = '/static/'
STATIC_ROOT = 'staticfiles'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'
Move your images to a folder name images inside your static folder
Then call your image in this way in your template file
<img src="{% static 'images/your_image.png' %}">

Related

How to show model images in Django?

I have such models.py file
class Product(models.Model):
CATEGORIES = {
('Computer', 'Комп\'ютер'),
('Smartphone', 'Смартфон')
}
photo = models.ImageField(upload_to='images/', blank=True)
title = models.CharField(max_length=128, blank=False)
description = models.CharField(max_length=5000, blank=False)
price = models.PositiveIntegerField(blank=False)
category = models.CharField(max_length=30, choices=CATEGORIES)
count = models.PositiveIntegerField(blank=False)
In settings.py i DON'T have media variables/dirs
Also i try to show images in such way
{% extends 'base.html' %}
{% block title %}Каталог{% endblock %}
{% block content %}
{% for i in products %}
<img src="{ static i.photo.url }">
{{i.title}}
{% endfor %}
{% endblock %}
Result:
I add my model objects in Django Admin
please see below configuration, have you done?
urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# urls/path
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
your HTML file
{% if i.photo %}
<img src="{{ i.photo.url }}">
{% endif %}
You don't need the static tag.
<img src="{{ i.photo.url }}">
You can add like this.
and run the collectstatic command to
<img src="{% static '/logo.png' %}"/>
python manage.py collectstatic
In settings.py i DON'T have media variables/dirs
you have to set MEDIA_ROOT and MEDIA_URL in settings.py and set the URL of each in urls.py because by default, Django stores files locally, using the MEDIA_ROOT and MEDIA_URL settings. The examples below assume that you’re using these defaults.
check the official doc.
step - 1
configure media and static files like this
add this in your settings.py
STATIC_ROOT = BASE_DIR / 'static_cdn'
STATIC_URL = '/static/'
MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_URL = '/media/'
STATICFILES_DIRS = [
BASE_DIR / "static",
]
and add this in your urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

How to load a static file in django2.0

I am having difficulty loading static files in django2.0 (coming from django1.4). Here is what I have so far:
# urls.py
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
# settings.py
TEMPLATES = [
...
'builtins': [
'django.contrib.staticfiles.templatetags.staticfiles',
],
]
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
STATIC_URL = '/static/'
STATIC_ROOT = ''
STATICFILES_DIRS = [
os.path.join(SITE_ROOT, "static"),
]
And I have one image located at:
[my_project_root]/static/img/image.png
Now if I go directly to the url, I get a 404:
http://localhost:8000/static/img/image.png
Additionally, if I do it "through the template", I also get a 404:
{% load static %}
<img src="{% static 'img/image.png' %}" alt="My image">
What do I need to add here to serve the static files?
This was a tricky setting. I needed to change the STATIC_ROOT to:
STATIC_ROOT = 'static/'
Otherwise, with STATIC_ROOT = '', it would look for the img file in [project_root]/img/image.png.

I can't see ImageField's photos in DJango's view [Solve]

something fail in my Django project, because the images that I load in the imagefields don't show in the view.
https://www.dropbox.com/sh/fvx6sfmxgm08xo6/AABVR-AQGeF52pCxlzVaLuDaa?dl=0
The crab's photo it's load with "static", but the second, that it's imagefield's photo.
enter image description here
Model:
class foto(models.Model):
nombre=models.CharField(max_length=50)
imagen=models.ImageField(upload_to='fotos/')
def __str__(self):
return self.nombre
View:
def general(request):
lista=foto.objects.all()
context={'material':lista}
return render(request,'indice.html',context)
settings:
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
STATICFILES_DIRS = (
'/media/fotos/',
)
html:
{% load staticfiles %}
<html>
<head>
<title>Album de fotos</title>
</head>
<body>
<img src="{% static 'cangrejo.jpg' %}" />
{% if material %}
{% for a in material %}
<li>{{a.nombre}}: {{a.imagen}}</li>
<img src="{{a.imagen}}" />
{% endfor %}
{% else %}
<p>No hay fotos</p>
{% endif %}
</body>
</html>
Admin's URLS:
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'',include('colecion.urls')),
]
View's URLS:
from django.conf.urls import url, include
from colecion import views
urlpatterns =[
url(r'^$',views.general),
]
Edit: I already solve the problem!
settings.py
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'ciencia/static')
models.py
foto=models.ImageField()
html
<img src="{% static alfa.foto %}" />
From the docs:
MEDIA_URL - "Absolute filesystem path to the directory that will hold user-uploaded files."
MEDIA_ROOT - "URL that handles the media served from MEDIA_ROOT, used for managing stored files. It must end in a slash if set to a non-empty value. You will need to configure these files to be served in both development and production environments."
Your current config's MEDIA_URL doesn't look right. It should be a URL, you have it set to a filesystem path. Try something like
MEDIA_URL = '/media/'
Add this to urls.py
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Change {{a.imagen}} to {{a.imagen.url}}

Django template doesn't display ImageField

I have a model where there is a ImageField but in the template doesn't appears. The upload of the image is OK (in media_root/one/image.jpg)
Settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media_root")
Urls.py
(...)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
Models.py
class myModel1(models.Model):
__(...)
__image = models.ImageField(upload_to='one', default="")
__(...)
And on my template, I make this:
<img src="{{ myModel1.image.url }}" alt="{{ myModel1.name }} image" />
And on the HTML is like:
(...)**src="/media/one/photo_p33Mo8a.jpg"**(...)
But the image is not displayed
error 404 not found:
GET http://localhost:8000/media/one/photo_p33Mo8a.jpg 404 (NOT FOUND)
Can someone help me?
PD: Sorry, my first time writing on stackOverFlow.
Have to comment that in the media_root/one/ there appears the image, but the folder /media/ is still empty.
FOLDER STRUCTURE:
Proyect:
___app_folder
________media
________models.py....
___media_root
________one
____________image.jpg
___mainFolder(settings,urls..)
___static_root(...)
Try in your tremplate:
<img src="{{ MEDIA_URL }}{{ myModel1.image }}" alt="{{ myModel1.name }} image" />
*EDIT
It seems you have to add in your urls.py file:
from django.conf import settings
from django.views.static import serve
# ... the rest of your URLconf goes here ...
if settings.DEBUG:
urlpatterns += [
url(r'^media/(?P<path>.*)$', serve, {
'document_root': settings.MEDIA_ROOT,
}),
]
Edit2
Your ROOT_MEDIA path should be:
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media_root")

Media files fail Django

I have a common problem with medias. I have a model which save an image in the media folder :
class Article(models.Model):
titre = models.CharField(max_length=100)
auteur = models.CharField(max_length=42)
contenu = models.TextField(null=True)
date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date")
photo = models.ImageField(upload_to="blog/media/upload/photos/", default="default.jpg")
But in my template when I try to get my picture by this way :
<img class="photo" src="{{ media_url }} {{ article.photo }}">
the {{ media_url }} is blank !
In my settings.py file I tried different configuration (found on this website), actually this is :
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
#MEDIA_URL = 'http://localhost:8000/blog/media/'
#MEDIA_ROOT = '/blog/media/'
MEDIA_ROOT = '/home/remi/perso/django/projets/SiteBlog/blog/media/'
ROOT_PATH = os.path.dirname(__file__)
STATICFILES_DIRS = (
os.path.join(ROOT_PATH, 'static'),
)
It works well for static files but not at all for media files.
I also tried to add in urls.py this :
# urlpatterns += patterns('',
# (r'^media/(?P<path>.*)$', 'django.views.static.serve', {
# 'document_root' : settings.MEDIA_ROOT}))
But with ths I get an "Syntax error".
Sorry to post for a common problem like that but I didn't find any working solution for me !
Thanks !
Rémi.
Fitst change {{ media_url }} with {{ MEDIA_URL }} in your template.
<img class="photo" src="{{ MEDIA_URL }} {{ article.photo }}">
And change urls.py like this:
if settings.DEBUG:
# static files (images, css, javascript, etc.)
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}))

Categories

Resources