简体   繁体   English

图像没有出现在Django模板中

[英]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: 我在上面设置了我的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'),
)

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. 调用使用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. 您必须在字段之前单独输出MEDIA_URL ,以便显示完整的URL。 Don't forget to use a RequestContext when rendering the template, and that the appropriate context processor is in place. 在渲染模板时不要忘记使用RequestContext ,并且适当的上下文处理器就位。

I am hoping this will help you 我希望这会对你有所帮助

change in setting.py 在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 '将你的apache链接到django静态文件夹

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

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

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