繁体   English   中英

图像没有出现在Django模板中

[英]Image not showing up in Django template

我在上面设置了我的settings.py文件,以获取模板和媒体的绝对路径:

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

我的模型看起来像这样:

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

在同步和创建模板后,我使用了变量

{{ work.sample }}

调用使用ImageField上传的图像。 运行服务器后,图像没有显示出来。 输出很简单

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

绝对路径未显示在标记中,因此未正确调用图像。 其他信息显示得很好。 任何人都可以帮我纠正这个问题吗? 我确信这是一个简单的解决方法,我无法弄明白。 顺便说一句,我在本地运行。 希望这是足够的信息。 谢谢。

您必须在字段之前单独输出MEDIA_URL ,以便显示完整的URL。 在渲染模板时不要忘记使用RequestContext ,并且适当的上下文处理器就位。

我希望这会对你有所帮助

在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/

'将你的apache链接到django静态文件夹

并使用<img src="{{ MEDIA_URL }}screenshots/2012/08/09/1.png />

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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