简体   繁体   中英

Image not showing up in Django template

I set up my settings.py file with this at the top to grab the absolute path for my templates and media:

import os.path
import django

DJANGO_ROOT = os.path.dirname(os.path.realpath(django.__file__))
SITE_ROOT = lambda x: os.path.join(os.path.abspath(os.path.dirname(__file__)), x)


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',

MEDIA_ROOT = SITE_ROOT('media'),
MEDIA_URL = '/media/'

TEMPLATE_DIRS = (
    SITE_ROOT('templates'),
)

and my model look like this:

class Work(models.Model):
    sample = models.ImageField(upload_to='screenshots/%Y/%m/%d/')
    name = models.CharField(max_length=200)
    url = models.URLField(blank=True)

After syncing and creating the templates, I used the variable

{{ work.sample }}

to call the image that was uploaded using ImageField. After running the server the image did not show up. The output was simply

<img src="screenshots/2012/08/09/1.png">

The absolute path is not showing up in the tag so the image is not being called properly. Other information is showing up just fine. Can anyone help me rectify this problem? I am sure this is a easy fix, I just can't figure it out. I am running this locally by the way. Hope this was enough information to go off on. Thanks.

You have to output MEDIA_URL separately before the field so that the full URL shows up. Don't forget to use a RequestContext when rendering the template, and that the appropriate context processor is in place.

I am hoping this will help you

change in setting.py

MEDIA_ROOT = '/path/to/static/folder/static'

 #Your static file location  
MEDIA_URL = 'http://localhost/static'  # i am asuming you are working on localhost

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/

' link your apache to django static folder

and use <img src="{{ MEDIA_URL }}screenshots/2012/08/09/1.png />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM