django ImageField链接不会在html模板

时间:2017-05-02 13:37:38

标签: python django profile

我可以通过管理员面板重定向到上传的图片,但我无法在页面上加载它。在HTML源代码中,它看起来像这样:

<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:

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 %}

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

要做的第一件事是检查代码生成的HTML。

我认为您不需要{{MEDIA_URL}},因为如果您的媒体设置正确,profile.avatar.url应该包含完整的网址。

<img src="{{ profile.avatar.url }}" height = "200" with = "200" />