ImageField upload_to in django 1.6 not displaying images to template - python

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.

Related

"Could not load the image" from Django's media folder

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.

django image upload to path is not displaying

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.

Serve images with Django

I am sending my images from my web server Django like follows :
localhost:8000/media/images/foo.png
My question is am I sending the images is the correct way? I think it is not necessary to send the server since I am the only one who serves the photographs. Any ideas, something like this media/images/foo.png.
In order that in the img tag of HTML this is a relative path and not a link.
For serving images in Django,
First make sure that you have your MEDIA_ROOT and MEDIA_URL defined inside the settings.py file.
Now let's say you have a model, models.py
class SomeModel(models.Model):
image = models.ImageField(upload_to = 'your_directory_inside_media')
#Rest of the fields
Next inside your views,
model_object = SomeModel.objects.get(...) #get an instance of model which has an ImageField
context = {'image' : model_object.image }
html = render(request , 'some_html.html' , context)
And finally inside your HTML,
{% load static %}
<img src="{% get_media_prefix %}{{ image.image }}">
Hope this helps. Thanks.

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 view images in django html template

I keep getting 404 error even though the url to the image is accurate. Yes, I have looked at official django docs and a whole lot of stackoverflow posts. I couldn't figure it out from those. If anyone can decipher what the instructions are saying to do then I will be grateful because they seem to be missing information.
index.html:
#I have tried static and staticfiles
{% load static %}
#a lot of code later...
<img border="0" src="{% static "logo.png" %}" alt="TMS" width="125" height="80">
Directory structure:
projectname
->__init__.py, settings.py, ...
manage.py
db.sql3
app_name
-> admin.py, models.py, views.py, templates->index.html, ...
static
->logo.png
The only thing about static that I have in settings.py along with 'django.contrib.staticfiles':
STATIC_URL = '/static/'
My views.py file has index function which returns HttpResponse(t.render(c)) where t is the index.html template and c is Context. Could those be the issue?
The url that results is this: http://127.0.0.1:8000/static/logo.png
You are using a static directory which is outside of your app (it is in the project folder), so in settings.py you need also:
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)

Categories

Resources