django ImageField link doesn't show in html template

ⅰ亾dé卋堺 提交于 2020-03-06 04:53:39

问题


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

So here's my code:

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

template:

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

Will be very thankful for any help.


回答1:


First thing to do is check the HTML generated by your code.

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


来源:https://stackoverflow.com/questions/43739363/django-imagefield-link-doesnt-show-in-html-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!