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)
Related
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 %}
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
I have a model where I have an image name, image description, and an image. I want to use these fields to display a div with the image description and name with the thumbnail for each row in my model. Right now when I am trying to render the template I am getting:
TypeError: 'ImageFieldFile object is not subscriptable
During handling of the above exception another error occured:
ImportError: No module named 'backends'
Code:
Models.py
class PictureType(models.Model):
name = models.CharField(max_length = 150)
description = models.CharField(max_length = 1000)
image = models.ImageField(upload_to='AppName/images/')
views.py
class indexView(generic.ListView):
model = PictureType
template_name = 'index.html'
index.html
{% for visual in object_list %}
<div class="col-sm-4">
<div class="thumbnail">
<a href="#" class="">
<div align="center" class={{ visual.name }}>
<h4 class="">{{ visual.name }}</h4>
<p class="">{{ visual.description }}
</p>
</div>
<img src= "{{ visual.image.url }}" alt="..." class="">
</a>
</div>
</div>
{% endfor %}
settings.py
MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'media')
MEDIA_URL = '/media/'
urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', indexView.as_view(), name = 'index'),
]
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
UPDATE:
When I change:
<img src= "{{ visual.image.url }}" alt="..." class="">
to
<img src= "{{ visual.image }}" alt="..." class="">
I don't get the above errors but the images don't come through either, they look like this:
Sounds like you are trying to import 'backends' module somewhere in your code, but it does not exist in the python path.
Hope this was helpful.
You have to tecth the Image URL from DataBase and Pass it to your HTML template file as context data type.
first you have to make sure that, you have been installed Pillow Library
(pip instal pillow)
And load static files to index.html file
{% load static %} - use this code on the begining of HTML
then change your view.py Function to :
class indexView(generic.ListView):
model = PictureType
users = PictureType.objects.all()
args = {'users':users}
template_name = 'index.html',args
or better way to Pass the data is change your Views as Function.
def indexView(request):
model = PictureType
users = PictureType.objects.all()
args = {'users':users}
return render(request,"index.html", args)
I can redirect to uploaded image through admin-panel but I can't load it on page. In HTML source code it looks like this:
<img src="" height = "200" with = "200" />
So here's my code:
models.py:
class Profile(models.Model):
user = models.ForeignKey(User)
avatar = models.ImageField(upload_to='images/users/', verbose_name='Аватар', default = 'images/users/ava.gif/')
urls.py:
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from mainpage.views import *
urlpatterns = [
#other urls
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + staticfiles_urlpatterns()
settings.py:
MEDIA_ROOT = 'C:/<<path to django app dir>>/media'
MEDIA_URL = '/media/'
template:
{% block content %}
<body>
<h1>{{ user.username }}</h1>
<img src="{{ MEDIA_URL }}{{ profile.avatar.url }}" height = "200" with = "200" />
<p>
<ul>
<li>email: {{ user.email }}</li>
</ul>
</p>
</body>
{% endblock %}
Will be very thankful for any help.
First thing to do is check the HTML generated by your code.
I don't think you need the {{ MEDIA_URL }} as profile.avatar.url should include the full url if you have your media settings correct.
<img src="{{ profile.avatar.url }}" height = "200" with = "200" />
I read a lot about including image files, but i still don't get it :(
my models.py
class Movie(models.Model):
image_url = models.URLField(max_length=1024, blank=True, null=True)
image_file = models.ImageField(upload_to='poster/', blank=True)
my index.html
{% load staticfiles %}
<img src="{% static "{{movie.image_file}}" %}" />
The pictures are saved on harddisk /myapp/poster
Thanks for helping.
Got it!
<img src="
{% if movie.image_file %}
{{ movie.image_file.url }}
{% else %}
another-image.jpg
{% endif %}"
/>
urls.py
+static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
added MEDIA_URL
Thanks a lot!
You just need to do:
<img src="{{ movie.image_file.url }}" />
User uploaded files go to your MEDIA_ROOT + the upload_to parameter in your model field, which is typically a different location that static files are served from when using the {% static %} template tag.
Since your field allows for blank=True you can use a conditional to show a different image, or no image at all: (spaces added to avoid wrapping)
<img src="
{% if movie.image %}
{{ movie.image_file.url }}
{% else %}
another-image.jpg
{% endif %}"
/>
alternatively, you could add a model property that does the same thing, or you can just wrap the entire image tag in the if statement to hide it if the field is empty.
Set MEDIA_ROOT and add following lines at the end of your urls.py
+static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Example:
urlpatterns = patterns('',
url(r'^$', views.index, name='Index'),
url(r'^admin/', include(admin.site.urls)),
) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
In img src write {{MODEL_NAME.FIELD_NAME.url}}
This is only for development.
Refer https://docs.djangoproject.com/en/1.8/howto/static-files/