I am having trouble on how to display an image on html? i just want to display all image that saves on my database
{% for banner in banners %}
<div class="mySlides fade">
<div class="numbertext">1 / 3</div>
<img class="d-block w-100" src="{{ banner.banner }}" style="width:100%">
<div class="text">{{banner.title}}</div>
</div>
{% endfor %}
model
class Banner(models.Model):
banner = models.ImageField(upload_to='image/', null=True, blank=True)
views
def homepage(request):
banners = Banner.objects.all()
return render(request, 'mysite/homepage.html', {'banners': banners})
result
enter image description here
Use the 'url' property of the ImageField.
Try this:
{{ banner.banner.url }}
models.py
class Banner(models.Model):
banner = models.ImageField(upload_to='image/', null=True, blank=True)
def get_banner_url(self):
return self.banner.url
html
{% for banner in banners %}
<div class="mySlides fade">
<div class="numbertext">1 / 3</div>
<img class="d-block w-100" src="{{ banner.get_banner_url }}" style="width:100%">
<div class="text">{{banner.title}}</div>
</div>
{% endfor %}
for be sure that your URL is coming try this(just for test):
<div class="text">{{banner.get_banner_url }}</div>
if you can't see the URL that means it is about your media tags
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
main urls.py
urlpatterns = [
#your paths
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Related
I am building a django blog website and I am trying to upload an image on the website. I can access the photos on the admin page but whenever I try to access it on the page I get an enroll. The trace back says
"
The 'image' attribute has no file associated with it.
This my code for the model
class article(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(User, on_delete=models.CASCADE)
content = models.TextField()
image = models.ImageField(null=True, blank=True, upload_to='static/media/article')
date = models.DateTimeField(default=timezone.now)
def __str__ (self):
return self.title
def get_absolute_url(self):
return reverse('article-detail', kwargs= {'pk':self.pk})
This is my views code
class ArticleCreateView(LoginRequiredMixin, CreateView):
model = article
fields= ['title', 'content', 'image']
def ArticleCreateView(request):
if request.method == "POST":
form = ArticleForm(request.POST, request.FILES)
if form.is_valid():
article = form.save(commit=False)
article.author = request.user.id
article.save()
return HttpResponse
this is the blog template code
{% extends "agri_tourism/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<section class="flex-container">
<div>
{% for article in articles %}
<article class="media content-section">
{% load static %}
<div class="media-body">
<div style="text-decoration:none; display: inline-block;" class="article-metadata">
<img class="rounded-circle article-img" src="{{user.profile.image.url}}">
<a style="text-decoration:none;" class="mr-2" href="#">{{ article.author }}</a>
<small class="article-date">{{ article.date|date:"F d, Y" }}</small>
</div>
<h2><a class="article-title" href="">{{ article.title }}</a></h2>
<p class="article-content">{{ article.content }}</p>
<img class="image-content" id="image-el" src = "{{article.image.url}}">
<div class="like-share-btns">
</div>
</article>
{% endfor %}
The form page code is below
{% extends "agri_tourism/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class = "content-section">
<div class = "container">
<div class = "row md-8">
<form method = "POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset class = "form-group">
<legend class ="border-bottom mb-4">Blog article</legend>
{{form|crispy }}
{{form.media}}
</fieldset>
<div class= "form-group">
<button class="btn btn-outline-info" type="submit" style= "margin-top:4px; ">Submit the Article</button>
</div>
</form>
</div>
</div>
</div>
I want to access photos on the blog page
check the image with if condition like this...
<div class="media-body">
<div style="text-decoration:none; display: inline-block;" class="article-metadata">
{% if user.profile.image.url %}
<img class="rounded-circle article-img" src="{{user.profile.image.url}}">
{% endif %}
<a style="text-decoration:none;" class="mr-2" href="#">{{ article.author }}</a>
<small class="article-date">{{ article.date|date:"F d, Y" }}</small>
</div>
and also check those settings
urls.py (in project directory)
from django.conf import settings # --------> this
from django.conf.urls.static import static # --------> this
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # --------> this
settings.py (in project directory)
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
When i run my code with the local server my images are not visualized, there are images icons but not the image itself.
settings.py:
MEDIA_URL = '/images/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images')
my template tienda.py:
{% extends 'tienda/index.html'%}
{%load static%}
{% block content %}
<div class="row">
{% for product in products %}
<div class="col-lg-4">
<img src="{{product.imageURL}}" alt="" class="thumbnail" >
<div class="box-element product">
<h6><strong>{{product.name}}</strong></h6>
<hr>
<button data-product={{product.id}} data-action="add" class="btn btn-outline-secondary add-btn update-cart">Agregar al carrito</button>
<a class="btn btn-outline-success" href="">Ver</a>
<h4 style="display: inline-block; float: right;"><strong>${{product.price|floatformat:2}}</strong></h4>
</div>
</div>
{%endfor%}
</div>
{% endblock %}
my model Product:
class Product(models.Model):
name = models.CharField(max_length=200, null=True)
price = models.FloatField()
digital = models.BooleanField(default=False, null=True, blank = False)
images = models.ImageField(null=True, blank=True)
WebSite
Admin Panel
First of all sorry for bad english. But i cant see my images on my website. I can see titles descriptions. Can you help me. I checked page resources it links my images and there is no problem.
thats exactly where my photos are
page resources
settings.py
STATIC_URL = '/static/'
MEDIA_URL = '/uploads/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')
template
<ul class="slides-container">
{% for rs in sliderdata %}
<li class="text-center">
<img src="{{ rs.image.url }}" alt="">
<div class="container">
<div class="row">
<div class="col-md-12">
<h1 class="m-b-20"><strong>Hoşgeldiniz <br> Site İsmi</strong></h1>
<p class="m-b-40">{{ rs.title}} <br> {{ rs.description }}</p>
<p><a class="btn hvr-hover" href="#">İncele</a></p>
</div>
</div>
</div>
</li>
{% endfor %}
views.py
def index(request):
setting = Setting.objects.get(pk=1)
sliderdata = Slider.objects.all()[:3]
category = Category.objects.all()
context={'setting':setting, 'page': 'home','category':category,'sliderdata':sliderdata}
models.py
class Slider(models.Model):
Status = (
('True', 'Evet'),
('False', 'Hayır'),
)
title = models.CharField(max_length=150)
description=models.CharField(max_length=255)
image = models.ImageField(upload_to='images/', blank=True)
create_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
It is because you added your images not in your templates. You should add
<img src="{{ rs.image.url }}">
I included the images in my database and store the images in the media directory. When I access my data from my database all information is loaded but my images are not showing. Can someone help me out?
This is my index.html file:
{% block body %}
{% load static %}
<div class="container">
<h1>Men Fashion</h1>
<div id="demo" class="carousel slide my-3" data-ride="carousel">
<ul class="carousel-indicators">
<li data-target="#demo" data-slide-to="0" class="active"></li>
{% for i in range %}
<li data-target="#demo" data-slide-to="{{i}}" ></li>
{% endfor %}
</ul>
<!--Slideshow starts here -->
<div class="container carousel-inner no-padding">
<div class="carousel-item active">
<div class="col-xs-3 col-sm-3 col-md-3">
<div class="card" style="width: 18rem;">
{% load static %}
<img src='/media/{{product.0.image}}' class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">{{product.0.product_name}}</h5>
<p class="card-text">{{product.0.desc}}</p>
Add to Cart
</div>
</div>
</div>
{% for i in product|slice:"1:"%}
<div class="col-xs-3 col-sm-3 col-md-3">
<div class="card" style="width: 18rem;">
<img src='/media/{{i.image}}' class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">{{i.product_name}}</h5>
<p class="card-text">{{i.desc}}</p>
Add To Cart
</div>
</div>
</div>
{% if forloop.counter|divisibleby:3 and forloop.counter > 0 and not forloop.last %}
</div><div class="carousel-item">
{% endif %}
{% endfor %}
</div>
</div>
</div>
<!-- left and right controls for the slide -->
<a class="carousel-control-prev" href="#demo" data-slide="prev">
<span class="carousel-control-prev-icon"></span>
</a>
<a class="carousel-control-next" href="#demo" data-slide="next">
<span class="carousel-control-next-icon"></span>
</a>
{% endblock %}
</div>
This is my models.py file which I included in my project:
from django.db import models
# Create your models here.
class Product(models.Model):
product_id = models.AutoField
product_name = models.CharField(max_length=50)
category = models.CharField(max_length=50, default="")
subcategory = models.CharField(max_length=50, default="")
price = models.IntegerField(default=0)
desc = models.CharField(max_length=300)
pub_date = models.DateField()
image = models.ImageField(upload_to='shop/images', default="")
def __str__(self):
return self.product_name
This is my setting.py file:
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
I do not know to much about this but..
Please have a look here:
Django image src not found
Similar problem to you, corrected by code.
In your model.py code, you say:
image = models.ImageField(upload_to='shop/images', default="")
and in your settings.py you have:
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/
I do not see where you declare a path to your images.
Try this code for your settings.py and see what works for you.
from django.core.files.storage import FileSystemStorage
from django.conf import settings
image_storage = FileSystemStorage(
# Physical file location ROOT
location=u'{0}/my_sell/'.format(settings.MEDIA_ROOT),
# Url for file
base_url=u'{0}my_sell/'.format(settings.MEDIA_URL),
)
def image_directory_path(instance, filename):
# file will be uploaded to MEDIA_ROOT/my_sell/picture/<filename>
return u'picture/{0}'.format(, filename)
class Goods(models.Model):
pic = models.ImageField(upload_to=image_directory_path, storage=image_storage)
For more information please see:
Django image src not found
Hope it helps.
First off, you should double-check where your images are actually being uploaded to.
Based on the ImageField, I'm guessing you want to store your product images to media/shop/images. In your template, however, you call /media/{{product.0.image}}, which will look for images in media/media/shop/images.
Secondly, remember that searches for the path to the image, not just the image itself. So try this:
<img src="{{product.0.image.url }}" class="card-img-top" alt="...">
I am facing problem showing image file in the django ecommerce project.Can anyone help in this issue?
home.html
{% for product in products %}
<div class='col-sm-4'>
<div class="thumbnail">
{% if product.productimage_set.all %}
{% for item in product.productimage_set.all %}
<img class='img-responsive' src="{{ MEDIA_URL }}{{ item.image}}" />
{% endfor %}
{% else %}
<img class='img-responsive' src="{% static "img/placeholder.svg" %}" />
{% endif %}
<div class="caption">
<a href='{{ product.get_absolute_url }}'> <h3>{{ product.title }}</h3></a>
<p>{{ product.description|truncatewords:15}}</p>
<p>View Button</p>
</div>
</div>
</div> {% endfor %}
model.py
class ProductImage(models.Model):
product = models.ForeignKey(Product)
image = models.ImageField(upload_to='products/images/')
featured = models.BooleanField(default=False)
thumbnail = models.BooleanField(default=False)
active = models.BooleanField(default=True)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
def __unicode__(self):
return self.product.title
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR),"static","media")
<img class='img-responsive' src="{{ MEDIA_URL }}{{ item.image.url }}" />
or
<img class='img-responsive' src="{{ item.image.url }}" />
and in main urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)