See my GitHub
https://github.com/rg3915/gallery
How to render images on Django template?
But he is returning:
Gallery
media/3665_1280x800_8UX8tgG.jpg
Tour de France
media/281405_fSRBDZu.jpg
bike of children
How to render the images?
Does the bug is in settings.py
urls.py
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from gallery.core.views import *
from django.contrib import admin
urlpatterns = patterns(
'gallery.core.views',
url(r'^$', 'home', name='home'),
url(r'^gallery/$', GalleryList.as_view(), name='gallery_list'),
url(r'^admin/', include(admin.site.urls)),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
MEDIA_ROOT = BASE_DIR.child('media')
MEDIA_URL = '/media/'
STATIC_ROOT = BASE_DIR.child('staticfiles')
STATIC_URL = '/static/'
gallery_list.html
<html>
<body>
<h1>Gallery</h1>
{% if gallery %}
{% for photo in gallery %}
<p><img src="{{ photo.photo.url }}" width="300px"></p>
<p>{{ photo.description }}</p>
{% endfor %}
{% endif %}
</body>
</html>
The secret is photo.photo.url
Related
I am getting broken images on django. Below are the relevant information with code, I guess. I am new to django and any information would be greatly appreciated.
name of project/site=imagesite
name of app=gallery
in models.py,
class Photo(models.Model):
pub_date = timezone.now()
image = models.ImageField(upload_to='images')
in views.py,
def view_gallery(request):
photo_list = Photo.objects.all()
return render(request, 'gallery/view_gallery.html', {'photo_list' : photo_list})
in view_gallery.html,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Gallery</title>
</head>
<body>
{% csrf_token %}
{% for photo in photo_list.all %}
<img src="{{ photo.image.url }}" width="240">
<h2> {{ photo.pub_date }} </h2>
<br>
{% endfor %}
</body>
</html>
in settings.py,
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'imagesite/media')
in imagesite/urls.py,
urlpatterns = [
path('imagesite/', include('gallery.urls')),
path('admin/', admin.site.urls),
]
in gallery/urls.py,
urlpatterns = [
path('', views.view_gallery, name='view_gallery'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Your static() urls should be added to the main urls.py file, not to your gallery/urls.py. Now you're prepending them with /imagesite/ so basically you're telling django to create urls /imagesite/media/ rather than /media/.
Also, just for clarity: This is a url setting that should only be used for development, not for production. So it's better to do like this in your main urls.py:
from django.conf import settings
urlpatterns = [
path('imagesite/', include(gallery.urls)),
...
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Finally, don't assume '/' for paths, as you see you're on Windows, so the path separator is a '\'. Your MEDIA_ROOT setting creates a folder "imagesite/media" rather than a folder "media" inside a folder "imagesite":
MEDIA_ROOT = os.path.join(BASE_DIR, 'imagesite', 'media')
I have a users app, profile is a model created in its models.py.The image is present in /media/profile_pics/ but even after giving the full path in src it is not loading. I cannot figure out why.Adding the relevant files below.
models.py
from django.contrib.auth.models import User
from django.db import models
from django.contrib.auth.models import AbstractUser
class profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='media/default.jpg', upload_to='profile_pics')
def __str__(self):
return f'{self.user.username} Profile'
profile.html
<!DOCTYPE html>
{% extends 'base2.html' %}
{% load crispy_forms_tags %}
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>profile</title>
</head>
{% block content %}
<body style="margin-left: 300px">
<div class="content-section">
<div class="media">
<img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
<img class="rounded-circle account-img" src="E:\py-projects\hello-world\media\profile_pics\profile1.png">
</div>
</div>
</body>
{% endblock %}
</html>
settings.py
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
print(MEDIA_ROOT)
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
urls.py(the main urls.py, not of app users)
from django.contrib import admin
from django.urls import path, include
from users.views import profile
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('users.urls'), name='index'),
path('profile/', profile, name='profile'),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
i feel stupid for not seeing this :| had to add this.
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Use this in your urls.py
from django.conf.urls import url
from django.conf import settings
from django.views.static import serve
urlpatterns = [
url(r'^media/(?P<path>.*)$', serve, {'document_root':
settings.MEDIA_ROOT}),
url(r'^static/(?P<path>.*)$', serve, {'document_root':
settings.STATIC_ROOT}),
]
And in your settings.py
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
I'm using Django building a website and I'm trying to let the user upload an image to be used, here is my files :
settings.py
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home2/media/media.lawrence.com/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media')
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'
models.py
class test1(models.Model):
dress_name = models.CharField(max_length=250, default='dress')
dress_size = models.CharField(max_length=50, default='5')
docfile = models.FileField(upload_to='documents/%Y/%m/%d',default ='upload')
views.py
def home(request):
all_dress = test1.objects.all()
context = {
'all_dress': all_dress,
}
return render(request, 'fostania/home.html', context)
and here is how I used it in my template
HTML
{% for item in all_dress %}
<div class="card" style="width: 18rem;">
<img class="card-img-top" src="{{ item.docfile.url }}" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">{{ item.dress_name }}</h5>
<p class="card-text">{{ item.dress_size }}</p>
Go somewhere
</div>
</div>
{% endfor %}
URLS.py
from django.contrib import admin
from django.template.context_processors import static
from django.urls import path
from django.contrib.auth import views as auth_views
from dress import settings
from fostania import views
urlpatterns = [
path('admin/', admin.site.urls),
path('login/', auth_views.login, name='login'),
path('home/',views.home, name='home'),
path('add/',views.add, name="add"),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
finally, the image never shows .. it is always an error in the link !!
Please note that image goes there in the static/media file after uploading, So i think it is some kind of URL error!
ERROR
The error is that the image always shows a broken link, and when I open the link (Open images link ) it gives me this error
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/media/documents/2018/05/18/test_dress3.jpg
You need to add MEDIA_URL to the project's urlpattern list:
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)
Check related part of the doc.
SOLVED
it was a wrong import reference, I used from django.conf.urls.static import static instead of from django.template.context_processors import static and it worked.
I have images I uploaded through django admin, but they are not displaying. The weird thing is that I have another project with the EXACT same code and it works. object.image.url outputs /media/media/image.jpg as does my other project. But this project does not show the image. if I put an image from my static folder or if I hardcode an image, it works fine. The problem is only when I try an image uploaded from the admin it does not work. Am I missing something in my settings.py file? or anywhere?
Models.py:
from django.db import models
# Create your models here.
class Connect(models.Model):
title = models.CharField(max_length=70)
short_description = models.TextField(null=True, blank=True)
description = models.TextField()
image = models.ImageField(upload_to='media', blank=True, null=True)
def __str__(self):
return self.title
views.py:
def index(request):
about = About.objects.all()
staff = Staffmembers.objects.all()
ministries = Ministries.objects.all()
connect = Connect.objects.all()
context = {
'template': 'home',
'connect': connect,
'about': about,
'staff': staff,
'ministries': ministries,
}
return render(request,'home/index.html', context)
template(index.html):
<div class="connect-wrapper row">
<h1 class="title connect-title">Connect</h1>
{% for object in connect %}
<div class="home-div connect-div col-md-4">
<h4>{{ object.title }}</h4>
<p>{{ object.short_description }}</p>
{% if object.image %}
<img class="connect-image-home" src="{{object.image.url}}" alt="connect">
<p>{{object.image.url}}</p> //sanity check
{% endif %}
</div>
{% endfor %}
</div>
settings.py:
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
urls.py:
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('home.urls'), name="home"),
]
I believe you need to add the media urls to your urls.py. Something like:
from django.conf import settings
from django.conf.urls import url
from django.conf.urls.static import static
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('home.urls'), name="home"),
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
On production environment Django does not load the media root automatically so that we can we can overcome that issue by adding following after url patterns:
urlpatterns = [
''''
your urls
''''
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
If you are using more than one app and including app urls on main app url, just add this on main project url.
Image uploaded by user is not displaying though i have not done wrong in template. Also i have defined MEDIA_URL and MEDIA_ROOT. What might be the reason for not getting image displayed?
Code
image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)
project/urls.py(urls.py of main project)
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('shop.urls', namespace='shop')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
Settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
templates/shop/product/list.html
<a href="{{ product.get_absolute_url }}">
<img src="{% if product.image %} {{ product.image.url }} {% else %} {% static 'img/no_image.png' %} {% endif %}" >
</a>
I know this question is asked multiple times but my code took after the documentation and still i could not display image. Could anyone help me, please?
It is working now after fresh restart of the server. So the above code and process of serving media files is correct.