图像没有在Django模板中显示模板标签

时间:2017-11-05 23:35:02

标签: django django-templates

我试图在我的HTML模板上显示用户上传的图片。我尝试了一堆模板标签,但它们似乎都没有工作。所有设置似乎都配置正确。用户上传的图片已正确上传到project_name/media/

settings.py

MEDIA_URL = '/media/'
MEDIA_ROOT = 'project_name'


# Are the STATIC settings affecting the media settings?  media is for user uploads so I don't think so?

STATICFILES_DIRS = [
    'project_name/static/',
]

STATIC_URL = '/static/'

我在这个HTML中尝试过的事情:

# 'app.profileapp' is not the issue here.  I can access other 'profileapp' attributes just fine (e.g. 'app.profileapp.agent_website' shows up just fine)
<img src = "{{ app.profileapp.agent_picture }}" alt='My image' />
<img src = "{{MEDIA_URL}}{{ app.profileapp.agent_picture }}" alt='My image' />
<img src = "{{MEDIA_ROOT}}{{ app.profileapp.agent_picture }}" alt='My image' />
<img src = "{{ app.profileapp.agent_picture.url }}" alt='My image' />
<img src = "project_folder/{{ agent.agentpremiuminfo.agent_picture }}" alt='My image' />
<img src = "project_folder/media/{{ agent.agentpremiuminfo.agent_picture }}" alt='My image' />

2 个答案:

答案 0 :(得分:0)

这是我的设置:

MEDIA_ROOT = os.path.join(BASE_DIR,"upload")

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/upload/'

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

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

<a href="/static/path/1.jpg"></a>

答案 1 :(得分:0)

假设我们的模型Posts的{​​{1}}字段名为ImageField。现在,在您的模板中(可以访问某些image实例),您可以显示包含以下内容的图像:

Post

其中<img src="{{ post.image.url }}"/> post的实例。

我确信这应该有效;我在我的网站上使用它;这是我的PostMEDIA_ROOT配置:

MEDIA_URL

重要提示:请务必在MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' 文件中加入以下内容:

urls.py

这将在开发期间为用户上传的媒体文件提供服务。有关详细信息,请查看here