show images in Django templates

42,070

Solution 1

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'),
)

Solution 2

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"

Solution 3

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)
Share:
42,070
hln
Author by

hln

Updated on April 19, 2021

Comments

  • hln
    hln about 3 years

    Can someone help me with this issue: I have a Django porject,

    in settings.py

     MEDIA_ROOT = 'C:/Users/hl/workspace/beer/media'
     MEDIA_URL = '/media/'
     STATICFILES_DIRS = (
        'C:/Users/hl/workspace/beer/media'
     )
    

    and in models.py

    image1= models.ImageField(upload_to=settings.MEDIA_ROOT)
    

    and in url.py

     (r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}),
    

    in views

    def allBeer(request): 
          beers=Beer.objects.all().order_by("name")
          context={'beers': beers}
          return render_to_response('AllBeers.html',context,context_instance=RequestContext(request))
    

    and in html

     {%for beer in beers %}
        <p>
            <a href="/beers/{{beer.slug}}/">
                <img scr="{{beer.image1.url}}">{{beer}}
            </a>
        </p>
     {% endfor%}
    

    It has not problem to load images, but images wont show in html file. I have searched and read a lot from internet but I still couldn't figure out.

    Can anyone tell me why?

  • hln
    hln about 11 years
    can't still not show the images with <img src="{{MEDIA_URL}}{{beer.image1}}">{{beer}}</a>
  • hln
    hln about 11 years
    can't still not show the images with <img src="{{beer.image1.url}}">{{beer}}</a> :(
  • Aidan Ewen
    Aidan Ewen about 11 years
    This should work if your on the dev server (ie using python manage.py runserver). If you're running it on a live server you will need to check your setup to correctly serve static files - this isn't handled by django, but by the webserver you have installed. For more info - docs.djangoproject.com/en/1.5/howto/static-files
  • hln
    hln about 11 years
    I use Django build-in server.
  • hln
    hln about 11 years
    i have changed to these codes, but nothing has changed, can still not show the images :(
  • Aidan Ewen
    Aidan Ewen about 11 years
    OK, try changing your url conf - loose the line you've included in your question and use the code in my updated answer.
  • hln
    hln about 11 years
    theProject beer init settings url beerApp admin models views (and so on) media (different pictures from uploading) templates html files manage.py (and so on)
  • hln
    hln about 11 years
    cant do anything with my low reputation:(, but the structure is like: porject(beer(settings.py, url.py ...)beerApp(views.py, models.py...)media('all images in upload to here')template('all html files')manage.py)
  • hln
    hln about 11 years
    still not work, where did i do wrong :O I need 10 to post a picture , thanks for you upvote :)
  • catherine
    catherine about 11 years
    There is something you have missed. We can try it again tomorrow, I need to sleep. Or maybe someone will help you later.
  • hln
    hln about 11 years
    thanks for your help, I will try to contact you again if I haven't solve the problem till tomorrow. have a nice dream. :)
  • hln
    hln about 11 years
    would yo still like to help me with that today, in you suggestion os.path.dirname(file), will point to my 'C:\\eclipse\\plugins\\org.python.pydev_2.7.1.2012100913\\py‌​src' folder, but i dont have any medie og static folder in this folder, it doesnt look like a good idea to create any new folder there:/
  • catherine
    catherine about 11 years
    Can we continue this in chat
  • catherine
    catherine about 11 years
    media folder is automatically created when you upload images
  • hln
    hln about 11 years
    where can i catch you in chat?
  • hln
    hln about 11 years
  • Jose Kj
    Jose Kj about 6 years
    sir @AidanEwen i accidently down voted your answer please edit your answer so that i can undo my downvote
  • Aidan Ewen
    Aidan Ewen about 6 years
    @JoseKj - thanks, I've updated the outdated link to the django docs
  • Nilanj
    Nilanj about 3 years
    it gives me 404, when I hit ip:8000:/media/project_name/photo.png.
  • Azharul Islam Somon
    Azharul Islam Somon about 3 years
    Sorry, do you have any photo in /media/project_name/ directory?
  • Nilanj
    Nilanj about 3 years
    oky, now its working , I was adding this static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) to app's urls.py file instead main urls.py file of main project directory.