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)
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/'
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)
I just want to display profile picture.Img upload successfully but not showing the img.But if i try in admin panel then show me img. Here is my index.html code
{% extends 'Login_app/base.html' %}
{% block body_block %}
{% if user.is_authenticated %}
<p>Hi {{ user_basic_info.username }},</p>
<p>Your Email {{ user_basic_info.email }}</p>
<p> Facebook Profile </p>
<img src="/media/{{ user_more_info.profile_pic }}" width="200px">
{% else %}
<div class="alert alert-primary"></div>You are not logged in!!</div>
{% endif %}
{% endblock %}
Here is my setting.py media setting
import os
MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # This is a tuple
MEDIA_URL = '/media/'
Here the ss of website
You have to add .url after the profile picture.
Try This:
<img src="/media/{{ user_more_info.profile_pic.url }}" width="200px">
OR
In Models.py define a get_absolute_url() method to join the media directory:
def get_absolute_image(self):
return os.path.join('/media', self.image.name)
And in templates do this:
{% for post in posts %}
<img src="{{ post.get_absolute_image }}" width="200px">
{% endfor %}
p.s.- here post is model name
django setting
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
django views
def single_article(request, page, slug):
article = get_object_or_404(Article, slug=slug)
return render(request, "article/single_article.html", locals())
django template
<`enter code here`img class="d-block w-100 img-responsive" style="height: 100%" src="{{ article.picture.url }}" alt="{{ article.title }}"
> Blockquote
you don't have to pass /media/ or use .url to fetch it from db
{% extends 'Login_app/base.html' %}
{% block body_block %}
{% if user.is_authenticated %}
<p>Hi {{ user_basic_info.username }},</p>
<p>Your Email {{ user_basic_info.email }}</p>
<p> Facebook Profile </p>
<img src="{{ user_more_info.profile_pic.url }}" width="200px">
{% else %}
<div class="alert alert-primary"></div>You are not logged in!!</div>
{% endif %}
{% endblock %}
this will work if still image is not loadin add you views
Try to add this code to the project's urls.py:
urlpatterns = [
...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
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 }}">
Django version 2.0
views.py
from django.views import generic
from .models import Album
class IndexView(generic.ListView):
template_name = 'music/index.html'
context_object_name = 'all_albums'
def get_queryset(self):
return Album.objects.all()
class DetailView(generic.DetailView):
model = Album
template_name = 'music/details.html'
details.html
{% extends 'music/base.html' %}
{% block body %}
<!-- {{album}} -->
<img src="{{album.album_logo}}">
<h1>{{album.album_title}}</h1>
<h3>{{album.artist}}</h3>
{% if error_message %}
<p><strong>{{ error_message }}</strong></p>
{% endif %}
<form action="{% url 'music:favorite' album.id %}" method="post">
{% csrf_token %}
{% for song in album.song_set.all %}
<input type="radio" id="song{{ forloop.counter }}" name="song" value="{{ song.id }}">
<label for="song{{ forloop.counter }}">
{{ song.song_title }}
{% if song.is_favorite %}
<img src="http://i.imgur.com/b9b13Rd.png" />
{% endif %}
</label><br>
{% endfor %}
<input type="submit" value="Favorite">
</form>
{% endblock %}
index.html
{% extends 'music/base.html' %}
{% block body %}
{% if all_albums %}
<h3>Here are all my Albums:</h3>
<ul>
{% for album in all_albums %}
<li>{{ album.album_title }}</li>
{% endfor %}
</ul>
{% else %}
<h3>You don't have any albums</h3>
{% endif %}
{% endblock %}
base.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Viberr</title>
{% load staticfiles %}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<link href='https://fonts.googleapis.com/css?family=Satisfy' rel='stylesheet' type="text/css">
<link rel="stylesheet" type="text/css" href="{% static 'music/style.css' %}" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<!-- Header -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#topNavBar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="{% url 'music:index' %}">University of Calicut</a>
</div>
<!-- Items -->
<div class="collaps navbar-collaps" id="topNavBar">
<ul class="nav navbar-nav">
<li class="active">
<a href="{% url 'music:index' %}">
<span class="glyphicon glyphicon-cd" aria-hidden="true"></span>
Albums
</a>
</li>
<li class="">
<a href="{% url 'music:index' %}">
<span class="glyphicon glyphicon-music" aria-hidden="true"></span>
Songs
</a>
</li>
</ul>
<form class="navbar-form navbar-left" role="search" method="GET" action="#">
<div>
<input type="text" class="form-control" name="q" value="">
<button type="submit" class="btn btn-default">Search</button>
</div>
</form>
<ul class="nav navbar-nav navbar-right">
<li class="">
<a href="#">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
Add Album
</a>
</li>
<li class="">
<a href="#">
<span class="glyphicon glyphicon-off" aria-hidden="true"></span>
Logout
</a>
</li>
</ul>
</div>
</div>
</nav>
{% block body %}
{% endblock %}
</body>
</html>
urls.py (music)
from django.conf.urls import url
from .import views
from django.urls import path
app_name = 'music'
urlpatterns = [
url(r'^$',views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>[0-9]+)/$',views.DetailView.as_view(), name='details'),
]
models.py
from django.db import models
class Album(models.Model):
artist = models.CharField(max_length=250)
album_title=models.CharField(max_length=500)
genre=models.CharField(max_length=100)
album_logo=models.CharField(max_length=1000)
def __str__(self):
return self.album_title + ' - ' + self.artist
class Song(models.Model):
album = models.ForeignKey(Album, on_delete=models.CASCADE)
file_type = models.CharField(max_length=10)
song_title = models.CharField(max_length=250)
is_favorite = models.BooleanField(default=False)
def __str__(self):
return self.song_title
I attached images of my home page and linked page,
please help me regarding the issue
n the above code, the second page is throwing me a error
django.urls.exceptions.NoReverseMatch: Reverse for 'favorite' not found. 'favorite' is not a valid view function or pattern name**
Please someone help me out where im wrong! Thanks in advance!
I can't see any url with the name favorite here, which is what the error is telling you as well:
app_name = 'music'
urlpatterns = [
url(r'^$',views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>[0-9]+)/$',views.DetailView.as_view(), name='details'),
]
you probably copy pasted the details.html or you simly forgot to specify the "favorite" url in the app "music"
EDIT:
As you have clarified that you are unable to solve the problem on your onw:
Change details.html as such:
<form action="{% url 'music:favorite' album.id %}" method="post">
replace it with
<form action="#" method="post">
you're site should then at least load.
EDIT2:
After watchich the youtube video you linked in your comment:
all the answers are in the video and its comments!
You didn't update details.html. Watch closely around min 1:50.
Btw my solution of replacing the form action will work as well, but the output will be slightly different from what you might expect...
I hope this will get you started ;)