django ImageField 链接未显示在 html 模板中 [英] django ImageField link doesn't show in html template
本文介绍了django ImageField 链接未显示在 html 模板中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以通过管理面板重定向到上传的图片,但我无法在页面上加载它.在 HTML 源代码中,它看起来像这样:
I can redirect to uploaded image through admin-panel but I can't load it on page. In HTML source code it looks like this:
<img src="" height = "200" with = "200" />
这是我的代码:
models.py:
class Profile(models.Model):
user = models.ForeignKey(User)
avatar = models.ImageField(upload_to='images/users/', verbose_name='Аватар', default = 'images/users/ava.gif/')
urls.py:
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from mainpage.views import *
urlpatterns = [
#other urls
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + staticfiles_urlpatterns()
settings.py:
settings.py:
MEDIA_ROOT = 'C:/<<path to django app dir>>/media'
MEDIA_URL = '/media/'
模板:
{% block content %}
<body>
<h1>{{ user.username }}</h1>
<img src="{{ MEDIA_URL }}{{ profile.avatar.url }}" height = "200" with = "200" />
<p>
<ul>
<li>email: {{ user.email }}</li>
</ul>
</p>
</body>
{% endblock %}
非常感谢您的帮助.
推荐答案
首先要做的是检查代码生成的 HTML.
First thing to do is check the HTML generated by your code.
我认为您不需要 {{ MEDIA_URL }} 因为如果您的媒体设置正确,profile.avatar.url 应该包含完整的 url.
I don't think you need the {{ MEDIA_URL }} as profile.avatar.url should include the full url if you have your media settings correct.
<img src="{{ profile.avatar.url }}" height = "200" with = "200" />
这篇关于django ImageField 链接未显示在 html 模板中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文