Django: How to show a picture from my database in a template? - python

I'm using Django, and trying to display a picture from my database. However, I am unable to.
Most of the code I am using is from this article.
This is my code.
My model("ingredient") uses:
title = models.CharField(max_length=50, primary_key=True)
pictureLink = models.ImageField(upload_to="media")
The pictureLink I provided in my database is:
C:\Users"Me"\Desktop"project"\image\leaves.png
My views.py contains:
def say_hello(request):
allimages = Ingredient.objects.all()
return render(request, 'hello.html', {'images' : allimages})
My HTML code is the following:
{% for img in images %}
<tr>
<td>{{img.title}}</td>
<td><img src="{{ingredient.pictureLink.url}}" width="120"/></td>
</tr>
{% endfor %}
In settings.py I put the following:
BASE_DIR = Path(__file__).resolve().parent.parent
MEDIA_ROOT = os.path.join(BASE_DIR, 'image')
MEDIA_URL = '/image/'
Where am I making a mistake? I'm a beginner with Django, so all feedback is appreciated!

first change your settings.py
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_URL = "/media/"
STATIC_URL = '/media/static/'
STATICFILES_DIRS = (BASE_DIR / 'media/static', )
STATIC_ROOT = 'media/staticfiles/'
second create a folder named media in your path
then add this to urlpatterns in your app urls.py to this:
url(r'^media/(?P<path>.*)/$', serve, {'document_root': settings.MEDIA_ROOT}, name = 'media'),
Do not forget to import these in the urls.py file in your application folder
from django.conf import settings
from django.conf.urls import url
from django.views.static import serve

Related

FileNotFound error when trying to download a file in django website

in my index.html I create a link to download a file
<ul>
{% for fil in listFiles %}
<li> {{ fil.csv_file.name }} </li>
{% endfor %}
</ul>
the listFiles object is generated from this model
from django.db import models
from django.conf import settings
class CsvDFile(models.Model):
csv_file = models.FileField()
file_path = models.TextField(max_length=200)
userID = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
In the html page the url is like this <li> test.csv </li>
However, when I click on it I get this error Not Found: /uploads/test.csv
I checked the folder and the file is in there and the folder 'uploads' is inside my app directory
Also in settings.py I set MEDIA_URL = 'uploads/' and MEDIA_ROOT = os.path.join(BASE_DIR, 'myapp/uploads')
The var BASE_DIR is referencing to my project directory
in settings.py BASE_DIR = Path(__file__).resolve().parent.parent
And my urls.py looks like this
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [..My views..]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_URL)
I don't know why it's not recognizing the file

Django - Unable to display an image from folder within media folder

I am trying to load an image from a folder within 'media' folder (media/tshrirts) onto template using django. Below is my settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
MEDIA_URL = '/media/'
#MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_ROOT = 'media'
**I tried both the roots none of them work.
Below is my models.py
from django.db import models
# Create your models here.
class tshirts(models.Model):
brand=models.CharField(max_length=50)
name=models.CharField(max_length=100)
price=models.DecimalField(max_digits=10, decimal_places=2)
image = models.ImageField(upload_to='tshirts/')
def __str__(self):
return self.name
this is part of the tshirts.html Why image.url is none??
<div class='tshirts'>
{% for eachtshirt in alltshirts %}
<div class='tshirt'>
{{eachtshirt.brand}}
<p>{{eachtshirt.name}}</p>
<p>{{eachtshirt.price}}</p>
<img src="{{eachshirt.image.url}}"/>
{% if eachshirt.image.url == None %}
<p>{{"Image Not Found"}}</p>
{% endif %}
</div>
{% endfor %}
</div>
finally, urls.py
urlpatterns = [
.
.
.
url(r'^tshirts/',include('tshirts.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
After I uploaded the image as an admin and clicked the link, the image was properly displayed.
http://127.0.0.1:8000/media/tshirts/t-shirt2.jpg - the image was displayed here.
How can I fix this, please let me know thanks!!!
Screenshot for the page
The root of your media, should include the BASE_DIR, like the following:
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
You have a typo in your template, you'are accessing {{eachshirt.image.url}} without t. the correct is
{{eachtshirt.image.url}} <!-- with t : each tshirt -->

Django Image Not found using template tags

I'm in trouble for many days now and all solutions given didn't helped me yet.
The image profile I want to show doesn't appear if I use the template variable {{ userprofile.photo.url}} (the result is the Alt text) but it does work when I put the path to the image like this : /dashboard/media/dashboard/photo/profils/user.png.
I've tried to debug, it seems the url is good but the result given is this :
[27/Nov/2017 13:55:07] "GET /dashboard/ HTTP/1.1" 200 44757
Not Found: /media/dashboard/photos/profils/user.png
[27/Nov/2017 13:55:07] "GET /media/dashboard/photos/profils/user.png HTTP/1.1" 404 2295
Here the files of the project :
Structure of the project :
project_dir/
dash-app/
__init__.py
settings.py
urls.py
wsgi.py
dashboard/
__init__.py
admin.py
app.py
forms.py
models.py
urls.py
views.py
...
templates/
dashboard/
index.html
...
static/
dashboard/
images/
logo9.png
...
media/
dashboard/
photos/
profils/
user.png
...
On the urls.py :
from django.conf.urls import url
from dashboard import models
from dashboard import views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
url(r'^$', views.index, name='index'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
On the settings.py :
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
STATIC_ROOT = os.path.join(BASE_DIR, "dashboard", "static")
#dashboard/media/
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "dashboard", "media", "dashboard")
On the models.py :
from django.core.files.storage import FileSystemStorage
image_storage = FileSystemStorage(
# Physical file location ROOT
location='{0}/'.format(settings.MEDIA_ROOT),
# Url for file
base_url='{0}/dashboard/'.format(settings.MEDIA_URL),
)
def image_directory_path(instance, filename):
# file will be uploaded to MEDIA_ROOT/dashboard/picture/<filename>
return 'photos/profils/{0}'.format(filename)
def logo_directory_path(instance, filename):
# file will be uploaded to MEDIA_ROOT/dashboard/picture/<filename>
return 'photos/logos/{0}'.format(filename)
...
# Photos
photo = models.ImageField(blank=True,
upload_to=image_directory_path,
storage=image_storage)
# Logo de l'activité
photo = models.ImageField(null=True,
upload_to=logo_directory_path,
storage=image_storage)
On the views.py :
def index(request):
connected = models.UserProfile.objects.get(user=request.user)
print(connected.photo.url)
context={
'userprofile':connected,
}
return render(request, 'dashboard/index.html', context)
On the index.html :
<!-- menu profile quick info -->
<div class="profile clearfix">
<div class="profile_pic">
{% if userprofile.photo %}
<img src="{{ userprofile.photo.url }}" alt="User" class="img-circle profile_img">
{% else %}
<img src="media/dashboard/photos/profils/user.png" alt="..." class="img-circle profile_img">
{% endif %}
</div>
<div class="profile_info">
<span>Bienvenu,</span>
<h2>{{ userprofile }}</h2>
</div>
</div>
<!-- /menu profile quick info -->
I'm using python 3 and Django 1.11.5
Thank tou for your help !
EDIT : I've opened the application on a private navigation to reload and see if there was someting on cache and know I see that nothing works, neither : {{ userprofile.photo.url|slice:"1:" }} or media/dashboard/photos/profils/user.png . Is ther something to reload the >media's file links to the project or something like that. Because If add the image manualy to the folder or if I upload it via Django Admin Interface, is there some difference ?
SOLVED : I changed these lines :
MEDIA_ROOT = os.path.join(BASE_DIR, "dashboard", "media", "dashboard") to MEDIA_ROOT = os.path.join(BASE_DIR, "dashboard", "media")
image_storage = FileSystemStorage(
# Physical file location ROOT
location='{0}/'.format(settings.MEDIA_ROOT),
# Url for file
base_url='{0}/dashboard/'.format(settings.MEDIA_URL),
)
to
image_storage = FileSystemStorage(
# Physical file location ROOT
location='{0}/dashboard/'.format(settings.MEDIA_ROOT),
# Url for file
base_url='{0}/dashboard/'.format(settings.MEDIA_URL),
)
Define a computed property on model that returns relative URL to media file.
class CustomUser(models.Model):
...
#property
def photo_url(self):
return '{}{}'.format(settings.MEDIA_URL, self.img)
Then use this computed property in template:
{% if userprofile.photo %}
<img
src="{{ userprofile.photo_url }}"
alt="User"
class="img-circle profile_img"
>
{% else %}
If you're running in development, you can register a route in your project urls for media files like so:
urlpatterns = [
...
] + static.static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Otherwise, consider uploading media files to a digital asset management system like Amazon S3 or writing server rules to serve your assets.
SOLVED :
I changed these lines :
MEDIA_ROOT = os.path.join(BASE_DIR, "dashboard", "media", "dashboard")
to
MEDIA_ROOT = os.path.join(BASE_DIR, "dashboard", "media")
image_storage = FileSystemStorage(
# Physical file location ROOT
location='{0}/'.format(settings.MEDIA_ROOT),
# Url for file
base_url='{0}/dashboard/'.format(settings.MEDIA_URL),
)
to
image_storage = FileSystemStorage(
# Physical file location ROOT
location='{0}/dashboard/'.format(settings.MEDIA_ROOT),
# Url for file
base_url='{0}/dashboard/'.format(settings.MEDIA_URL),
)

Django ImageField upload_to path

I'm having trouble understanding and using Django's ImageField.
I have a model:
class BlogContent(models.Model):
title = models.CharField(max_length=300)
image = models.ImageField(upload_to='static/static_dirs/images/')
description = models.TextField()
My file system is currently:
src
|---main_project
|---app_that_contains_blog_content_model
|---static
|---static_dirs
|---images
When I run the server and go to the Admin page, I can add BlogContent objects. After choosing an image for the image field, the image has a temporary name. However, after I save this object I can't find the image in the folder specified by the upload_to path.
What is the correct way to do this?
Your image would be uploaded to the media folder, so it's better to change path in the model like images/, and they will be upload to media/images
In settings.py add this
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
In url.py
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [....
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And then, if you want to display all this image, use something like this
in view.py
BlogContent.objects.all()
And render it like this:
{% for img in your_object %}
<img src="{{ img.image.url }}" >
{% endfor %}
static in upload_to doesnot make sense, since user-uploaded images go into media/ folder.. you need these:
image = models.ImageField(upload_to='blog/%Y/%m/%d')
and all images land in:
media/blog/2016/01/02/img_name.jpg
you access it in template like this:
<img src="{{ blog.image.url }}">
in settings:
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
You should use media path, instead static. See docs

how to access upload images

I am creating one app using following two url's , homepage.html and detail.html.
*models.py*
class News(models.Model):
primary_image = models.ImageField("Main Image ",upload_to = "static/uploadedImg/main",)
secondary_Image = models.ImageField("Sub Image",upload_to = "static/uploadedImg/sub",)
In settings.py I had defined MEDIA and MEDIA_ROOT
I want to display random primary_image in homepage.html with primary_image as a link.
*articles.html*
<div id = "randommainImage">
<img src = "{{random_object.primary_image}}">
</div>
NewArticles
articles
db.sqlite3
manage.py
media
NewsArticles
README.md
static
NewsArticles\articles
admin.py
forms.py
models.py
static
Templates
tests.py
urls.py
views.py
Also, I want to display both primary_image & secondary_Image in a detail.html
Can anybody help me?
If you've defined correctly MEDIA and MEDIA_ROOT, to display the first image in the article.html template you use:
<img src = "{{ MEDIA_ROOT }}{{ random_object.primary_image }}" />
and likewise in the detail.html template:
<img src = "{{ MEDIA_ROOT }}{{ random_object.primary_image }}" />
<img src = "{{ MEDIA_ROOT }}{{ random_object.secondary_image }}" />
If you have these in your settings properly then you're ready to go:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media")
MEDIA_URL = '/media/'
A folder called media will be created to upload all the images in that folder.
Your image fields should look like this, I don't get why are you creating a folder for them in the static folder..
primary_image = models.ImageField(upload_to='uploadedImg/main/')
secondary_image = models.ImageField(upload_to='uploadedImg/sub/')
So your primary image will be in media/uploadedImg/main/img.png
View can look like:
def index(request):
context_dict = {}
news = News.objects.all()
context_dict['news '] = news
return render(request, 'index.html', context_dict, )
And to get the primary image you'll use {{ news.primary_image.url }} in your template.
edit>
Add this in your urls.py
from django.conf import settings
# ... your normal urlpatterns here
if settings.DEBUG:
# static files (images, css, javascript, etc.)
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}))

Categories

Resources