Django can't show images on page - python

I'm desperatly trying to load some images to and from my database with the help of Django.
Loading seems to work, but getting them back from the database and showing them on a webpage doesn't seem to work.
Here some info:
Environment:
myproject
|_forpix(my app)
|_myproject
|_media
|_images
|_mimicry3.png
I have a base.html wich includes a contentblock "allimages.html":
{% extends "base.html" %}
{% block content %}
<div id="imagelist">
{% for image in images %}
<p><img src="{{MEDIA_ROOT}}{{image.picture.url}}" />{{ image }}</p>
{% endfor %}
</div>
{% endblock %}
This gives me the following result:
And if I click on one of the images i get:
In my settings.py I've set the following:
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates/'),)
Now i really don't know how to fix this.
Can anybody provide me with some help (not the django tutorial, I've been there, tried that)
Do I have to add something in the urls.py especially for the media file? Or is it something else?
If i need to provide extra info, just ask.

^media/$ is a very wrong regex for media files. You should delete the $ (end-of-the-string) sign from this regex.
Usually for development environments I use this snippet in the urls.py:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Also remove the useless {{ MEDIA_ROOT }} part from your template code. It should be:
<img src="{{ image.picture.url }}" />

In adition the line that you have to add is..
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
But it has to be in the urls.py of your project folder. not in the urls.py of your App folder. I knew it by mistake.

Related

add image to FileField in Django

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.

Django geting error when loading static files?

I have the code below to load static files, but I keep getting a TemplateSyntaxError. Does anyone know how I can fix this issue?
Template:
{% load staticfiles %}
{% load static %}
<img class="logo" alt="Test Pic" src="{% static 'images/logo.png' %}" width="110" height="70">
{% block main %}
{% endblock %}
Settings:
INSTALLED_APPS = [
...,
'django.contrib.staticfiles',
]
STATIC_URL = '/public/'
STATIC_ROOT = os.path.join(BASE_DIR, "public")
URLS:
urlpatterns = [
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Error I get:
Invalid block tag on ...: 'static', expected 'endblock'. Did you forget to register or load this tag?
Just use {% load static %} on the top since it is recommended in newer versions of Django. I think using staticfiles and static at the same time creates a confusion.
What fixed the issue was reinstalling Django.

user uploaded image is not displaying

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.

Display images on Django Template Site

I read a lot about including image files, but i still don't get it :(
my models.py
class Movie(models.Model):
image_url = models.URLField(max_length=1024, blank=True, null=True)
image_file = models.ImageField(upload_to='poster/', blank=True)
my index.html
{% load staticfiles %}
<img src="{% static "{{movie.image_file}}" %}" />
The pictures are saved on harddisk /myapp/poster
Thanks for helping.
Got it!
<img src="
{% if movie.image_file %}
{{ movie.image_file.url }}
{% else %}
another-image.jpg
{% endif %}"
/>
urls.py
+static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
added MEDIA_URL
Thanks a lot!
You just need to do:
<img src="{{ movie.image_file.url }}" />
User uploaded files go to your MEDIA_ROOT + the upload_to parameter in your model field, which is typically a different location that static files are served from when using the {% static %} template tag.
Since your field allows for blank=True you can use a conditional to show a different image, or no image at all: (spaces added to avoid wrapping)
<img src="
{% if movie.image %}
{{ movie.image_file.url }}
{% else %}
another-image.jpg
{% endif %}"
/>
alternatively, you could add a model property that does the same thing, or you can just wrap the entire image tag in the if statement to hide it if the field is empty.
Set MEDIA_ROOT and add following lines at the end of your urls.py
+static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Example:
urlpatterns = patterns('',
url(r'^$', views.index, name='Index'),
url(r'^admin/', include(admin.site.urls)),
) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
In img src write {{MODEL_NAME.FIELD_NAME.url}}
This is only for development.
Refer https://docs.djangoproject.com/en/1.8/howto/static-files/

How can I use user uploaded files in my templates? (django)

So far I made it to the part where a user uploads an image but how can I use those images which are located in my media folder? Here is what I tried :
my view:
#I even tried to import MEDIA_ROOT to use it in my template...
#from settings import MEDIA_ROOT
def home(request):
latest_images = Image.objects.all().order_by('-pub_date')
return render_to_response('home.html',
#{'latest_images':latest_images, 'media_root':MEDIA_ROOT},
{'latest_images':latest_images,},
context_instance=RequestContext(request)
)
my model:
class Image(models.Model):
image = models.ImageField(upload_to='imgupload')
title = models.CharField(max_length=250)
owner = models.ForeignKey(User)
pub_date = models.DateTimeField(auto_now=True)
my template:
{% for image in latest_images %}
<img src="{{ MEDIA_ROOT }}{{ image.image }}" width="100px" height="100px" />
{% endfor %}
and my settings.py MEDIA_ROOT and URL:
MEDIA_ROOT = '/home/tony/Documents/photocomp/photocomp/apps/uploading/media/'
MEDIA_URL = '/media/'
So again here is what I am trying to do: Use those images in my templates!
If you use the url attribute, MEDIA_URL is automatically appended. Use name if you want the path without MEDIA_URL. So all you need to do is:
<img src="{{ some_object.image_field.url }}">
On development machine, you need to tell the devserver to serve uploaded files
# in urls.py
from django.conf import settings
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
)
{# in template, use sorl-thumbnail if your want to resize images #}
{% with image.image as img %}
<img src="{{ img.url }}" width="{{ img.width }}" height="{{ img.height }}" />
{% endwith %}
# furthermore, the view code could be simplified as
from django.shortcuts import render
def home(request):
latest_images = Image.objects.order_by('-pub_date')
return render(request, 'home.html', {'latest_images':latest_images})
On production environment using normal filesystem storage, ensure the webserver has permission to write to MEDIA_ROOT. Also configure the webserver to read /media/filename from correct path.
ImageField() has an url attribute so try:
<img src="{{ MEDIA_URL }}{{ image.image.url }}" />
You could also add a method to your model like this to skip the MEDIA_ROOT part:
from django.conf import settings
class Image(...):
...
def get_absolute_url(self):
return settings.MEDIA_URL+"%s" % self.image.url
Also I'd use upload_to like this for sanity:
models.ImageField(upload_to="appname/classname/fieldname")
Try these settings:
import socket
PROJECT_ROOT = path.dirname(path.abspath(__file__))
# Dynamic content is saved to here
MEDIA_ROOT = path.join(PROJECT_ROOT,'media')
if ".example.com" in socket.gethostname():
MEDIA_URL = 'http://www.example.com/media/'
else:
MEDIA_URL = '/media/'
# Static content is saved to here
STATIC_ROOT = path.join(PROJECT_ROOT,'static-root') # this folder is used to collect static files in production. not used in development
STATIC_URL = "/static/"
STATICFILES_DIRS = (
('', path.join(PROJECT_ROOT,'static')), #store site-specific media here.
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
For Django version 2.2., try the following:
#You need to add the following into your urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
Your URL mapping
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #add this
# And then use this in your html file to access the uploaded image
<img src="{{ object.image_field.url }}">
You have to make the folder containing the uploaded images "web accessible", i.e. either use Django to serve static files from the folder or use a dedicated web server for that.
Inside your template code, you have to use proper MEDIA_URL values.

Categories