Images cannot be shown in html.I wrote codes in models.py
class POST(models.Model):
title = models.CharField(max_length=100)
image = models.ImageField(upload_to='images/', blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
in views.py
def top(request):
content = POST.objects.order_by('-created_at')[:5]
return render(request, 'top.html',{'content':content})
in top.html
<div>
{% for item in content %}
<div>
<h2>{{ item.title }}</h2>
<img src="{{ item.image }}"/>
</div>
{% endfor %}
</div>
When I access in browser, html is shown.<h2>{{ item.title }}</h2> is shown but <img src="{{ item.image }}"/> is not there.When I see page source in GoogleChrome,<img src="/images/photo.jpg"/> is shown. But when I click the url,404 error happens.My application has image/images folder, in images folder surely my uploaded picture is in there.I really cannot understand why this happens.I wrote MEDIA_ROOT&MEDIA_URL in settings.py so I think image is shown in browser. How should I fix this?
make sure your /images folder is visitable in Django. an easy way to get it done is to add the "images" folder in settings.py. like:
IMAGE_URL = '/images/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "images"),
'/images/',
]
Then in your html file add {% load images %} on the top.
First make sure you have these lines in your project urls file
# Your imports ....
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [.......]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And in your template use
{{ item.image.url }}
Use relative folder:
<img src=".{{ item.image }}"/>
resulting in
<img src="./images/photo.jpg"/>
and check if the upload worked and the image is there.
Try this: <img src="/image{{ item.image }}"/>
/ : means "Root"
. : means "Current directory"
so if your root application has image folder you need to start your path with /image
Related
I am trying to build an e-commerce website using python's Django framework as part of a practice project. However, I am not being able to display my product's image on my landing page.
Django version: 3.2.4
models.py:
class Listing(models.Model):
title = models.CharField(max_length=100)
price = models.FloatField()
description = models.TextField()
image = models.ImageField(upload_to="auctions/images/", default="")
settings.py:
STATIC_URL = '/static/'
# Managing media
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
urls.py:
from django.contrib import admin
from django.urls import include, path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("auctions.urls"))
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py
def index(request):
listings = Listing.objects.all()
return render(request, 'auctions/index.html', {
"listings": listings
})
index.html
{% extends "auctions/layout.html" %}
{% load static %}
{% block body %}
<h2>Active Listings</h2>
{% for listing in listings %}
<div class="card" style="width: 18rem;">
<img class="card-img-top" src="{% static listing.image %}" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">{{ listing.title }}</h5>
<p class="card-text">{{ listing.description }}</p>
<p class="card-text">Price - {{ listing.price }}</p>
Bid
</div>
</div>
{% endfor %}
{% endblock %}
I am only getting the alt attribute for the img tag.
As mentioned by #Pruthvi Barot you need to change the code you are using in your html from
src="{% static listing.image %}"
to
src="{% url listing.image.url %}"
That is because you image as a media and allowing them to served via a url as you define here:
# Managing media
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
The static file are in this case images that you placed in the directory and do not manage (upload and delete) from the Django Admin Panel.
another solution mentioned by #MojixCoder is to replace the above mention line of code with
src="{{ listing.image.url }}"
This is the preferred solution and is the one specified in Djangos official documentation on MEDIA_URL (version 3.2)
I am new to django and I am trying to build web site for my friend how makes handmade lamps.
My problem is that I have 3 different models that contains different types of lamps, and I want to get access to certain picture in any of this 3 models and display a picture and description on the other page,but it shows only some pictures from first model and for others throws an error.
this is my html and views.py codes.
{% for q in project1.reverse|slice:":2"%}
<div class="image-selected__lamps">
<a href="{% url 'project_detail' q.pk%}">
<img src="{{q.image.url }}">
</a>
</div>
{%endfor%}
{% for e in project2.reverse|slice:":2"%}
<div class="image-selected__lamps">
<a href="{% url 'project_detail' e.pk %}">
<img src="{{e.image.url}}">
</a>
</div>
{%endfor%}
{% for s in project3.reverse|slice:":2"%}
<div class="image-selected__lamps">
<a href="{% url 'project_detail' s.pk %}">
<img src="{{s.image.url}}">
</a>
</div>
{%endfor%}
enter image description here
def project_detail(request, pk):
project = (LampType1.objects.get(pk=pk), LampType2.objects.get(pk=pk), LampType3.objects.get(pk=pk))
context = {
'project': project,
}
return render(request, 'project_detail.html', context)
Edward this might be happening because you are passing the same id/pk to all the models and you got a picture from the first model and not from the other because an object with that id/pk does not exit in the other models.
To check, register your models in the admin and check weather an object with that particular id exit or not.
check if these steps have been done
model
class LampType1(models.Model):
title = models.CharField(max_length=40)
description = models.TextField()
image = models.ImageField(upload_to='media')
#not
#image = ImageField(upload_to='media')
settings.py
MEDIA_URL = 'media/'
MEDIA_ROOT = Path.joinpath(BASE_DIR,'media')
urls.py
from django.conf.urls.static import static
from django.conf import setting
urlpatterns = [.....
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
from django.contrib import admin
html
{% for p in project %}
<img src="{{ p.image.url }}">
{% endfor %}
I cannot show images which is url type.
I wrote in product.html
<body>
{% for product in products.all %}
<h4> {{ product.product_title }}</h4>
<img src="{% static product.image }} %}"/>
<p> {{ product.body }} </p>
{% endfor %}
</body>
in models.py
class Product(models.Model):
product_title = models.CharField(max_length=250)
image = models.TextField()
body = models.TextField()
in views.py
def product(request):
products = Product.objects.order_by('product_title')
return render(request, 'registration/product.html',{'products':products})
From admin site,I added product_title&image&body.
image's urls is
<a href="https://xxxxxx" target="_blank" rel="nofollow">
<img border="0" width="120" height="60" alt="" src="https://wwwyyyyyyyyyyyy"></a>
<img border="0" width="1" height="1" src="https://wwwzzzzzzzzzz" alt="">
By using Google console,Failed to load resource: the server responded with a status of 404 (Not Found) is in Console.
In Elements,img tag is like
<img src="/static/wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww">
How can I show image?Am I wrong to write the way of img tag & src?
If you want to use pictures in Django, you have to configure your application like this :
First step : Static and Media
In your settings.py file, write something like this :
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]
PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static/')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join('path_to_your_Media_directory')
Second step : Implement Image field in your model
In your models.py file :
Image = models.ImageField(upload_to='upload_file_directory', null=True, blank=True, width_field=None, height_field=None, default=" ")
Third step : Handle image in your view
In your views.py file (don't forget request.FILES or None !) :
if request.method == 'POST':
form = 'YourForm'(request.POST or None, request.FILES or None)
if form.is_valid() :
post = form.save()
And in your template, don't forget enctype="multipart/form-data" in your form class
Fourth step : Call your image in your template
{% if 'your_image_exist' %}
<img src='{{Model.Image.url}}' height="300" width="400"/>
{% endif %}
It's a global example, but you have to set all these things in order to handle picture with Django !
Good luck
Your image is not a static file. Since its a textfield and its content is a url you just have put the value in the src attribute. There is no need of using the static tag.
Try this:
<img src="{{ product.image }}"/>
In my project i had set my media folder like this:
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
urls.py
urlpatterns = [
....
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
then in my models.py i create a class like this one:
class PD_Pictures(models.Model):
pic_IDmod = models.ForeignKey(PD_Models, related_name='modello')
pic_image = models.ImageField()
pic_descr = models.CharField(max_length=50)
def __str__(self):
return self.pic_descr
at this point in my function in views.py I extract all values in db related to PD_Picture:
prod_img = PD_Pictures.objects.all()
.....
return render(
request,
'base_catalog.html',
{
'bike_mod': bike_models,
'prod_img': prod_img,
'cat_list': cat_list,
'menu_list': menu_list['menu'],
'pcontent': menu_list['cont'],
'form': c_form
},
context
)
and in my template, i would ti display related images:
{% for pic in prod_img %}
<div class="4u">
<span class="image fit"
<img src="{{ pic.pic_image }}" alt="" />
</span>
</div>
{% endfor %}
Well, at this point when I insert a new image in db, in table the path is newimage.jpg, physically on my server the image was stored in /media/newimage.jpg, how can I extract the value from the table and concatenate to the media path in my template? (<server>/media/newimage.jpg)
I have tried to use upload_to='/models/' in my ImageField but the only effect is to save image into another model folder into main model.
just try like this
{% for pic in prod_img %}
<img src="{{ pic.pic_image.url }}" alt="" />
{% endfor %}
From django official doc:
FieldFile.url
A read-only property to access the file’s relative URL by calling the url() method of the underlying Storage class.
if you try to print in your template {{ pic.pic_image }} you'll receive the db field value, while with {{ pic.pic_image.url }} the url() method from django.core.files.storage.Storage will call, and your base settings
would seem to be correct
Can you make this into your template and see what path is given?
{% for pic in prod_img %}
<p>{{ pic.pic_image }</p>
{% endfor %}
this is the code in my models file:
from django.db import models
class Studio(models.Model):
.....
.....
metroimage = models.ImageField(upload_to='images', blank=True)
this is the code on the template file:
{% for place in studio %}
.....
.....
<img class="metro" src="{{ place.metroimage.url }}"><b>{{ place.metro }}</b><br>
{% endif %}
but when the page displays i get this (this is source-code)
.....
.....
<img class="metro" src="/http://momo.webfactional.com/media/images/m3.png"><b>Zara</b><br>
what's with the forward slash before http? i can't get the uploaded image to display...
I'd guess your MEDIA_URL settings (in settings.py) is to blame for the extra slash.