I have an application where I upload images and the images are uploaded to a specific directory but after uploading which works fine if I attenp to click on the image url I get an error which says
The current URL, media/gallery/2017/12/28/230-256.png, didn't match any of these and also the image is not displaying in the browser html
below is my model and view despite having my media path defined in the settings
Models.py
class Gallery(models.Model):
name = models.CharField(max_length=400, db_index=True)
image = models.ImageField(upload_to='gallery/%Y/%m/%d', blank=True)
class Meta:
ordering = ('name',)
def __str__(self):
return self.image.url
Views.py
def index(request):
gallery = Gallery.objects.all()
context = {
'gallery': gallery,
}
template = 'gallery.html'
return render(request, template, context)
html
{% if gallery.image %}
<div><img src="{{ gallery.image.url }}"></div>
{% endif %}
While you are developing, in the project urls.py you must add
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This will make your uploaded file accessible by the application.
When on a production server, it is better if the webserver itself (apache, nginx, ..) can reach the location where the files are uploaded, you can find how to configure that in other answers (here for nginx, and here for apache
Your HTML needs to be something like this:
{% if gallery.image %}
<div><img src="{{ MEDIA_URL }}{{ gallery.image.url }}"></div>
{% endif %}
MEDIA_URL should be configured in settings.py. This should be set to the base URL from where you're serving the files stored in MEDIA_ROOT.
The URL attribute of the image field stores only the relative URL of the image.
Related
So I've been trying to get the images uploaded through admin interface to render on a template but for some odd reason it just wont render the images. It renders any other type of data but NOT IMAGES.
From Settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
From appvew.py:
class ProjectsListView(ListView):
model = Projects
context_object_name = 'projects'
template_name = 'myportfolio/portfolio.html'
appurls.py:
urlpatterns =[
path('home/', views.ProjectsListView.as_view()),
# path('projects/', )
]
html template:
{% load static %}
</head>
<body>
<h1><p>This is my portfolio</p></h1>
{% for project in projects %}
<img src="{{project.screenshot}}" alt="No image found">
{% endfor %}
</body>
</html>
Error message on the terminal:
Not Found: /portfolio/home/projects/images/shutterstock_253580635_square.jpg
Not Found: /portfolio/home/projects/images/mountains.jpg
[25/Mar/2022 14:16:06] ←[33m"GET /portfolio/home/projects/images/shutterstock_253580635_square.jpg HTTP/1.1" 404 2560←[0m
[25/Mar/2022 14:16:06] ←[33m"GET /portfolio/home/projects/images/mountains.jpg HTTP/1.1" 404 2500←[0m
output :( :
I verified an old project of mine with pretty much the same set up and it works. This one on the other hand, only renders the name of the objects on other properties but not the images
Try this
<img src="{{project.screenshot.url}}" alt="No image found">
https://docs.djangoproject.com/en/4.0/topics/files/
I have trouble displaying images stored in a file server to the django template.
File server link is \11234.123.123.123\dashboard.jpg (just a sample).
It seems like the img src url is being added by the django localhost url prefix to the file server path as follows: http://127.0.0.1:8000/dashboard/\\11234.123.123.123\dashboard.jpg
In django template, the img tag is written as:
<img class="imgView" src="{{dashboard_image}}" alt="Dashboard画面.jpg"></img>
My views.py just sends the image file server URL as text (with value of \11234.123.123.123\dashboard.jpg) to be displayed as image in the HTML page as the django template.
def dashboard(request):
dashboard_image_url = '\\11234.123.123.123\dashboard.jpg' #TODO temporary, just sample
context = {'dashboard_image': dashboard_image_url}
return render(request, 'dashboard.html', context)
But, the image does not show properly as follows.
Please help, thank you!
In your template instead of:
<img class="imgView" src="{{dashboard_image}}" alt="Dashboard画面.jpg"></img>
DO this:
<img class="imgView" src="{{dashboard_image.url}}" alt="Dashboard画面.jpg"></img>
<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'm trying to display an image from a database (SQLite, Django2.7). These images are stored in root/media/pictures.
models.py
class News(models.Model):
news_id = models.AutoField(primary_key=True, editable=False)
news_img = models.FileField(upload_to="pictures/",validators=[FileExtensionValidator(allowed_extensions=['svg'])] )
urls.py
urlpatterns = [...]
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
I've try to insert the path in the var in the following methods:
template.html
{% for news_f in news_f%}
<div>
<img src="{{ media }}{{news_f.news_img}}">
</div>
{% endblock %}
and
{% for news_f in news_f%}
<div>
<img src="{{news_f.news_img.url}}">
</div>
{% endblock %}
When I inspect the element in the browser, I get the correct path to the file.
<img src="/media/pictures/file.svg">
But it isn't displayed in the HTML:
Could not load the image
That happens because django doesn't serve static files. Usually you use django along with some webserver like nginx and those servers are more reliable serving files.
Please check out django docs https://docs.djangoproject.com/en/2.2/howto/static-files/deployment/
Your configuration for media files is right, the problem is that Django doesn't serve SVG files with the right mime type by default, this answer explains how to make it work.
Currently using Django 1.9.
Image files in my model are uploading properly to
project\media\FILEPATH.jpg
However, images are attempting to be displayed using the filepath without \media. For example, when I go to my localhost http://127.0.0.1:8000/media/FILEPATH.jpg in my browser, I get a 404 because Django's get request is looking for:
project\FILEPATH.jpg
How do I get django to serve my media files properly with \media\?
More information if it may be of any use:
settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.dirname(os.path.join(BASE_DIR, 'media'))
model:
image = models.ImageField(upload_to='media', blank='true')
project urls.py I have the following after urlpatterns as per the documentation:
static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Thank you for any help!
models.py
class Post(models.Model):
ptype = models.ForeignKey('blog.Type', related_name='posts')
title = models.CharField(max_length = 100)
text = models.TextField()
published_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.title
class Image(models.Model):
post = models.ForeignKey('blog.Post', related_name='images')
image = models.ImageField(upload_to='media', blank='true')
views.py
class Posts(generic.ListView):
model = Post
context_object_name = 'posts'
template_name = 'blog/posts.html'
posts.html
{% extends "blog/base.html" %}
{% block content %}
{% for post in posts %}
<p>{{post.title}}</p>
<p>{{post.text}}</p>
{% for image in post.image_set.all %}
<img src="{{ image.image.url }}">
{% endfor %}
{% endfor %}
{% endblock %}
Ok
When your declare the upload on the model, Django detect automatically that your route of media is BASE_DIR/media, when you put somthing in upload_to on the model you are declare that this image have to saved on BASE_DIR/media/something
Example: if I want to save the user's images into media I have to make this on the model
image = models.ImageField(upload_to='users/', blank='true')
and my image will saved on localhost/media/users/FILEPATH.jpg
All this url after media/ is saved on your field of 'image' so your image field will say just 'users/FILEPATH.jpg' but not the localhost/media/
Thats why you need to write the /media/ in you src
<img src="/media/{{ image.image }}">
and if you save the image on the field named 'image' your will not need the .url.
Try it.
In my django application, I have created a django model with an ImageField.
The problem is that the image itself is not getting rendered on the template. However, the image path is displayed on the template itself.
Also when I look in my media folder, I can see that the images that I uploaded are stored there.
My media root configuration in settings.py is as follows:
MEDIA_URL = '/media/'
MEDIA_ROOT = ("D:/Work-Backup/LiClipse Workspace/vTryON_DJango_Integration/vTryON/templates/media"
)
My models.py is as follows
from django.db import models
class VTryON(models.Model):
modelId = models.CharField(max_length=100)
slug= models.SlugField(unique=True)
image=models.ImageField(upload_to="images/framethumbs/", help_text="not more than 1MB", default ='D:/Work-Backup/LiClipse Workspace/vTryON_DJango_Integration/vTryON/templates/static/images/frame2.jpg')
def __unicode__(self):
return unicode(self.modelId)
and my template is
<html lang="eng">
<head>
<title>vTryOn Attempt Using Django Framework</title>
</head>
<body class="body">
{{frame.image}}
</body>
</html>
The image path that is displayed on the template looks like this
images/framethumbs/fr_5.jpg
I have created a folder images/framethumbs under the MEDIA_ROOT url where all the images are stored. can it be a permission issue?
If so then, how and where do I give permissions?
I am using a Windows 7 PC. Thanks in advance.
Please make sure you have an entry in urls.py to server the static files, if not add this to urls.py file..
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}))
Now to get the image you should use an image tag like this...
<img src="{{ frame.image.url }}" />
Hope this helps.