UPDATE: I solved this by adding urls
urlpatterns = patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),)
I use sorl-thumbnail to create image.
It really create the image in directory,but it can't get the path (firebug said 404 not found)
please help me to check.
Thank you very much.
settings.py
THUMBNAIL_DEBUG = True
MEDIA_URL = '/media/'
MEDIA_ROOT= os.path.join(BASE_DIR, 'media')
template: menu.html
{% load thumbnail %}
{% thumbnail "https://www.google.com.tw/images/srpr/logo11w.png" "100x80" as im %}
<img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}">
{% endthumbnail %}
Related
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)
I'm new to Django. In my app, I'm working on an image uploading and displaying function. I have tried setting up the MEDIA_URL and Media_ROOT. I also add the static path to the urls.py file and make sure that in HTML template object.image.url is used. However, the image is not displayed. Any help is greatly appreciated!
Edit 1 (Add project structure):
This is a screenshot of my project structure:
link to my project structure screenshot
Edit 2 (Add screenshots of browser):
link to browser screenshot
django admin page
the image in browser
Edit 3 (Add screenshot of browser inspect window)
image of browser inspect window
My code is as followed:
urls.py
from django.contrib import admin
from django.urls import include, path
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("auctions.urls"))
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py
class ListingForm(ModelForm):
def __init__(self, *args, **kwargs):
super(ListingForm, self).__init__(*args, **kwargs)
for field in iter(self.fields):
self.fields[field].widget.attrs.update({
'class': 'form-control'
})
class Meta:
model = Listing
fields = ['title', 'description', 'current_price', 'image', 'category']
def index(request):
return render(request, "auctions/index.html", {
"active_listings" : Listing.objects.all()
})
def createListing(request):
if request.method == "POST":
listing_data = ListingForm(request.POST, request.FILES)
if listing_data.is_valid():
title = listing_data['title']
description = listing_data.cleaned_data['description']
current_price = listing_data.cleaned_data['current_price']
if listing_data.cleaned_data['image']:
image = listing_data.cleaned_data['image']
else:
image = None
category = listing_data.cleaned_data['category']
listing = Listing(title=title, description=description, current_price=current_price, image=image, category=category)
listing.save()
return HttpResponseRedirect(reverse("index"))
return render(request, "auctions/createListing.html", {
"listingForm" : ListingForm()
})
models.py
class Listing(models.Model):
class Category(models.TextChoices):
FASHION = 'FA', _('Fashion')
TOYS = 'TO', _('Toys')
ELECTRONICS = 'EL', _('Electronics')
HOME = 'HO', _('Home')
OTHERS = 'OT', _('Others')
title = models.CharField(max_length=64)
description = models.TextField()
current_price = models.IntegerField()
image = models.ImageField(upload_to='listingImages', blank=True)
category = models.CharField(max_length=64, blank=True, choices=Category.choices)
settings.py
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
index.html
{% extends "auctions/layout.html" %}
{% block body %}
<h2>Active Listings</h2>
<ul>
{% for listing in active_listings %}
<li>Title: {{ listing.title }}</li>
<li>Description: {{ listing.description }}</li>
<li>Current Price: {{ listing.current_price }}</li>
{% if listing.image %}
<li>
<img scr="{{ MEDIA_URL }}{{ listing.image.url }}" alt="{{ listing.image.url }}">
</li>
{% endif %}
{% endfor %}
</ul>
{% endblock %}
createListing.html
{% extends "auctions/layout.html" %}
{% block body %}
<h1>Create A New Listing</h1>
<form action="{% url 'createListing' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{% for field in listingForm %}
<div class="form-group">
{{ field.label }} {{ field }}
</div>
{% endfor %}
<input type="submit" value="Done">
</form>
{% endblock %}
Replace src attribute in your img tag from this:
scr="{{ MEDIA_URL }}{{ listing.image.url }}"
to this:
scr="{{ listing.image.url }}"
Also you can try to add a line like this to check if image exists at all:
{% if listing.image %}
<li>
<img scr="{{ MEDIA_URL }}{{ listing.image.url }}" alt="{{ listing.image.url }}">
</li>
{% else %}
<p> Image doesnt exist. </p>
{% endif %}
UPDATE
Try making your main urls.py like this:
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("auctions.urls"))
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
Instead of what you have right now.
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)
I've created a simple django blog, and I'm having trouble getting images to consistently show up in my posts. Specifically, my images appear in the "list" view (the home page for the site), but not in the "detail" view (when viewing one individual post). The website is here if you want to see the issue live: endicott.co
The code for the list view is below:
{% extends "blog/base.html" %}
{% block title %}endicott.co{% endblock %}
{% block content %}
<div class="page-header">
<h1>endicott.co</h1>
<p>Perspectives on society, data, and economics</p>
</div>
{% for post in posts %}
<h2>
<a href="{{ post.get_absolute_url }}">
{{ post.title }}
</a>
</h2>
<p class="date">
Published {{ post.publish }} by {{ post.author }}
</p>
<img src="{{ post.image.url }}" alt="img">
{{ post.body|linebreaks }}
{% endfor %}
{% include "pagination.html" with page=page_obj %}
{% endblock %}
The code for the detail view is listed below:
{% extends "blog/base.html" %}
{% block title %}{{ post.title }}{% endblock %}
{% block content %}
<h1>{{ post.title }}</h1>
<img src="{{ post.image.url }}" alt="img">
<p class="date">
Published {{ post.publish }} by {{ post.author }}
</p>
{{ post.body|linebreaks }}
{% endblock %}
Any thoughts on why django is correctly showing the image in the list but not the detail view? Let me know if I should post any additional code for more background.
The file structure is as follows:
blog/
-__pycache__/
-migrations/
-templates/
--blog/
---post/
----detail.html
----list.html
---base.html
--pagination.html
-__init__.py
-admin.py
-apps.py
-models.py
-tests.py
-urls.py
-view.py
media/
-img/
--[where images are stored]
mysite/
-__pycache__/
-static/
-__init__.py
-settings.py
-urls.py
-wsgi.py
My blog urls.py file is below:
from django.conf.urls import url
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# post views
#url(r'^$', views.post_list, name='post_list'),
url(r'^$', views.PostListView.as_view(), name='post_list'),
url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/'\
r'(?P<post>[-\w]+)/$',
views.post_detail,
name='post_detail'),
]
if settings.DEBUG:
urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
The mysite urls.py file is below:
from django.conf.urls import include, url
from django.contrib import admin
##### adds
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'', include('blog.urls',
namespace='blog',
app_name='blog')),
]
if settings.DEBUG:
urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Your problem is that the src= is understood as a relative URL (just like saq7 pointed). You want the image to have its src= pointing to an absolute URL (starting with http://) since the image sits at an absolute location from the website root (from the domain).
To perform that, you shall use {% media post.image.url %}. Note that for that you need to perform a couple of additions to settings.py, notably MEDIA_ROOT and MEDIA_URL, in order for the {% media %} template tag to work.
Using media files in this fashion (with {% media %}) is the most common and accepted way. Note that in production (i.e. behind a real webserver) such files shall not be server by Django, note how that article has:
This is not suitable for production use!
Yet, there is another article in the Django documentation explaining what to do to configure your webserver to serve these files.
Also, if you set MEDIA_URL = '/media/' you will need to remove the media/ prefix from post.image.url.
I have question how to load media in my template
I use sorl-thumbnails to create thumbnails
and I want to show the picture in template
Here is my settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT= os.path.join(BASE_DIR, 'media')
MEDIAFILES_DIRS = (
("cache", os.path.join(MEDIA_ROOT,'cache')),
)
my templates : english/maininfo.html
{% load staticfiles %}
{% load thumbnail %}
<ul id="menu">
<li>
{% thumbnail "http://www.test/img/logo.png" "100x80" as im %}
<img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}">
{% endthumbnail %}
</li>
there is error :
The current URL, media/cache/d8/fe/d8fe70d567ce1a03769de7db30634696.jpg, didn't match any of these.
But I really have this directory
this is the project structure
and my views.py
def maininfo(request):
responseContext = {'lang':request.LANGUAGE_CODE,}
return render(request, 'english/maininfo.html',responseContext)
How to load media files in templates??
Please help me! Thank you very much