问题
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