[Fixed]-Show images in Django templates

10👍

image1= models.ImageField(upload_to=images)


from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from project_name import settings

admin.autodiscover()
urlpatterns = patterns('',
    ...........
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

urlpatterns += staticfiles_urlpatterns()


<img src="{{MEDIA_URL}}{{beer.image1}}">

settings.py

import os

PROJECT_ROOT = os.path.join(os.path.dirname(__file__), '..')
SITE_ROOT = PROJECT_ROOT


MEDIA_ROOT = os.path.join(SITE_ROOT, 'media')
MEDIA_URL = '/media/'


STATIC_ROOT = os.path.join(SITE_ROOT, 'static')
STATIC_URL = '/static/'


STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    os.path.join(SITE_ROOT, 'staticfiles'),
)

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    os.path.join(SITE_ROOT, 'templates'),
)

8👍

You’re messing with the src attribute of the image. It should just be –

<img src="{{beer.image1.url}}" /> <!-- from the media url -->

Don’t add anything to the end – django know’s the url to serve the image from – that’s what the ImageField on the model does.

I don’t know that there’s actually anything wrong with your url conf, but the pattern recommended in the docs is –

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = patterns('',
    # ... the rest of your URLconf goes here ...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

7👍

Follow this steps to load an image on your Django Template:

  1. Add this to your settings file:
    
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
  1. Create a folder named “media” under your project root directory, meaning the folder will be on the same level as your apps

  2. Add these to your main urls.py

from . import views, settings
from django.contrib.staticfiles.urls import static

urlpatterns = [
    # ... the rest of your path goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
  1. In your model, use ImageField for the field being used for the image.
    
photo = models.ImageField(upload_to="gallery")
  1. Add below to your template to load your images

If you are loading dynamically from a context object, use a syntax similar to this:

    
img src="{{ obj1.photo.url }}"

If you are loading statically, when the file name is already determined, use:

img src="/media/project_name/photo.png"

0👍

the location of your images are important. it has to be in the static folder and that has to be defined in the settings.

Leave a comment