Not able to display image in django - django

files of whole project
I have correctly setup path for media url and still not able to find images in allproducts.html where as in categories.html it is able to find images from media directory. I am not able understand the cause of this bug.
allproducts.html
{% for sub in subcategory %}
{% for p in sub.product_set.all %}
<div class="product">
<div><h3 class="logo header_content d-flex flex-row align-items-center justify-content-start">{{sub.name}}</h3></div>
<div class="product_image"><img src="media/{{p.image}}" alt=""></div>
<div class="product_content">
<div class="product_title">{{p.name}}</div>
<div class="product_price">{{p.price}}</div>
</div>
</div>
{% endfor %}
<div></div>
{% endfor %}
settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
STATIC_DIR,
]
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
urls.py
urlpatterns = [
path('',views.index, name="index"),
path('cart',views.cart, name="cart"),
path('categories',views.categories, name="categories"),
path('checkout',views.checkout, name="checkout"),
path('contact',views.contact, name="contact"),
path('product/<int:pk>/',views.product, name="product"),
path('allproducts/<int:pk>/', views.allproducts, name="allproduct"),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py
def allproducts(request, pk):
products = Product.objects.all()
category = Category.objects.get(pk=pk)
subcategory = Subcategory.objects.filter(category = category)
return render(request, 'shop/allproducts.html',
{'products':products, 'subcategory':subcategory,
'category':category})
project files
kh
kh
.idea
__init__.py
settings.py
urls.py
wsgi.py
media
shop
images
test.jpg
shop
db.sqlite3
manage.py

You will certainly need a leading slash:
<img src="/media/{{p.image}}" alt="">
But better to let the image itself output its full path:
<img src="{{p.image.url}}" alt="">

Related

Django: media files doesn't load up uploaded by user in production environment

I'm hosting my site in railway. Everything is set up and works fine but the images uploaded by user don't load up.
settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static')
]
MEDIA_URL ='/media/'
MEDIA_ROOT = os.path. join(BASE_DIR,'media')
models.py
class Post(models.Model):
img = models.ImageField(upload_to="pics")
blog.html
{% extends 'base.html' %}
{% load static %}
{% static "images/projects" as baseUrl %}
{% for post in post_list %}
<div class="image_wrapper"><a href="{% url 'post_detail' post.slug %}" target="_parent"><img
src="{{ post.img.url }}" alt="image 1"/></a></div>
{% endfor %}
urls.py
urlpatterns = urlpatterns + static(settings.MEDIA_URL,document_root= settings.MEDIA_ROOT)
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Error I'm getting:
Not Found: /media/pics/CC_Tech_Computers_1_6rgae2m.jpg
Not Found: /media/pics/CC_Tech_Computers_1_6rgae2m.jpg
Not Found: /media/pics/CC_Tech_Computers_1_6rgae2m.jpg
Not Found: /media/pics/CC_Tech_Computers_1_6rgae2m.jpg
instead of this:
src="{{ post.img.url }}"
Try this way:
src="/media/pics/post.img"
And in your models.py:
img = models.ImageField(upload_to="pics/") #Here added `forward slash (/)`
Try this way and see if it loads the image

Django media image file is not displaying in template

I have a problem with media files in Django 4.0.4, here are the code and some screenshots to understand the problem :
Settings.py
STATIC_URL = 'static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'
MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_URL = '/media/'
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('sites_events.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
models.py
photo = models.ImageField()
index.html
{% load static %}
<h1>{{ object.title }}</h1>
<p>{{ object.description }}</p>
<p>link: {{ object.link }}</p>
<p>Category: {{ object.category }}</p>
<p>Date: {{ object.date_time|date }} at {{ object.date_time|time }}</p>
{% for photo in photo_list %}
{{photo.photo.url}}
<img scr="{{ photo.photo.url }}" width="250" height="250">
{% endfor %}
If I copy the img src URL, e.g. http://127.0.0.1:8000/media/canvas_gb9uMM8.png, the image is well displayed.
Thank you for your help.
If you can't use ImageField it mean you 'photo' in photo = models.FileField(). Don't had any data(image). That mean even you call it, it will display not thing. Because the photo field don't had anything to display.

media folder images are not displaying in Template Page

I'm new to Django. Medial folder images are not displaying in Template file. please help me in that.
models.py
class Images(models.Model):
image = models. ImageField(upload_to='images', blank=True, null=True)
settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
urls.py
urlpatterns = [
......
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py
def image_display(request):
image_obj = Images.objects.all()
return render(request, 'index.html', {'image_obj': image_obj})
index.html
<body>
{% for item in myoffers_objs %}
<div>
<img src="{{ item.image.url }}" alt="Images"/>
</div>
{% endfor %}
</body>
Project details where i did mistake. why its displaying like this.
Image displaying like this
The for loop in the template file is incorrect.
Try this
<body>
{% for item in image_obj %}
<div>
<img src="{{ item.image.url }}" alt="Images"/>
</div>
{% endfor %}
</body>
correct static_root:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
you have to add this to your html file if you use statics in that html:
{% load staticfiles %}
also you have to run this command to collect static files in your project:
python manage.py collectstatic

How to fix "Not Found" problem for displaying images?

I'm preparing a blog component of a site, it is created inside an app of a project. It seems that there is no problem except the images are not displayed.
while running, all things are OK, but just the image "alt" is displayed instead of the image. I have images without problem in other pages of this project.
There is a report on Terminal:
"Not Found: /article/static/images/growth_EWAl68g.png
[14/Apr/2019 17:44:38] "GET /article/static/images/growth_EWAl68g.png HTTP/1.1" 404 6164"
As you can see, Django uses a false address (static folder is located in root of projects) to access the images.
class BlogArticle(models.Model):
title = models.CharField(max_length=150)
headline = models.CharField(max_length=300)
body = models.TextField()
post_image = models.ImageField(upload_to ="static/images")
date = models.DateTimeField(auto_now_add=True)
author = models.CharField(max_length=100)
def __str__(self):
return self.title
class ArticleListView(ListView):
model = BlogArticle
template_name = 'article_list.html'
urlpatterns = [
path('', views.HomeView, name= 'home'),
path('article/', views.ArticleListView.as_view(), name='article_list'),
path('article/<int:pk>/', views.ArticleDetailView.as_view(), name='article_detail'),
.
.
.]
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('allauth.urls')),
path('contactus', include('sendemail.urls')),
path('', include('myapp.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
{% block content %}
<div <div class="container mt-5 bg-light">
{% for article in object_list %}
<div class="form-row">
<div class="form-group col-sm-9 ">
<div class="post-entry">
<h5 > <a href = "{% url 'article_detail' article.pk %}" > {{ article.title }}</a></h5>
<div>
<p class="font-weight-bold"> {{article.headline }} </p>
</div>
<div>
<span class="text-muted">by {{article.author }} | {{ article.date|date:"M d, Y"}}</span>
</div>
</div>
</div>
<div class="form-group col-sm-3 ">
<div class="thumbnail">
<img src="{{article.post_image}}" width=100 height=100 class="rounded" alt="{{article.title}}">
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock content %}
.
DEBUG = True
ALLOWED_HOSTS = []
.
.
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),]
.
.
I can't understand this condition, It seems that Django should go to static/images/ but it has an extra word (article) at the beginning of the address.
This problem was simply solved by adding
urlpatterns +=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
to project's urls.py and
MEDIA_URL = '/media/'
in settings.py.

Django 1.9: Unable to see uploaded photos

I have some photos uploaded but I was unable to see photos in temeplates
My template
{% extends 'base.html' %}
{% load staticfiles %}
{% block content %}
<div class="row ">
<div class="col-md-8">
<h1>{{ object.title }}</h1>
{% if object.productimage_set.count > 0 %}
<div>
{% for img in object.productimage_set.all %}
{{ img.image.file }}
{{ img.image.url }}
<img class='img-responsive' src='{{ img.image.url }}' />
</div>
{% endfor %}
</div>
{% endif %}
<div class="lead">{{ object.description }}</div>
</div>
</div>
My model
class Product(models.Model):
title = models.CharField(max_length=120)
description = models.TextField(blank=True, null=True)
price = models.DecimalField(decimal_places=2, max_digits=20)
active = models.BooleanField(default=True)
def __unicode__(self): # def __str__(self):
return self.title
class ProductImage(models.Model):
product = models.ForeignKey(Product)
image = models.ImageField(upload_to='product/')
Setting for media
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static", "my_static"),
]
STATIC_ROOT = os.path.join(BASE_DIR, "static", "static_root")
STATIC_URL = '/media/media_root/'
MEDIA_ROOT = os.path.join(BASE_DIR, "static", "media_root")
My urls
urlpatterns = [
url(r'^contact/', views.contact, name='contact'),
url(r'^$', views.ProductViewList.as_view(), name='ProductViewList'),
url(r'^(?P<pk>\d+)/$', views.ProductDetailView.as_view(), name='Product_Detail'),]
My folder structure
In the template {{ img.image.url }} gives -> product/mp3.jpg. But still I'm unable to see the image
The console shows that image is loaded from http://127.0.0.1:8080/product/1/product/mp3.jpg I guess there is some prob with the url to collect the image but not sure
Any help is much appreciated....Thanks in advance
You should add the MEDIA_URL to your settings.py, if you haven't.
In your case, the MEDIA_URL should be media_root. My Image links all have /media/....jpg.
In addition, you can specify the URLs:
from django.conf import settings
if settings.DEBUG:
# static files (images, css, javascript, etc.)
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}))
Here's some documentation from Django on this: https://docs.djangoproject.com/en/1.9/howto/static-files/#serving-files-uploaded-by-a-user-during-development
I prefer keeping my media files separate from my static files, so during development I actually store mine in the project root. The following snippets use the project root as the media location, but you can easily adjust this by changing it to static/media_root if you'd prefer to keep your current location.
First make sure you've defined your media root in your settings.py file:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Then try adding the following to your project's urls.py file:
from django.conf import settings
if settings.DEBUG:
urlpatterns += patterns('', (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}))