我正在使用Django 1.9.3。我正在尝试显示由用户说出的媒体文件(例如imageFields)。
HTML页面:
{% for project in projects %}
<img src="{{ project.image.url }}" class="img-responsive" alt="">
{% endfor %}
Views.py:
def home(request):
projects = AvailableProject.objects.all().order_by('-published_date')
return render(request, 'accounts/home.html', {'projects': projects})
urls.py:
urlpatterns = [
...
]
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = (
('global', os.path.join(BASE_DIR, 'smilesite', 'project_static')),
('admins', os.path.join(BASE_DIR, 'admins', 'static')),
('accounts', os.path.join(BASE_DIR, 'accounts', 'static')),
('mysite', os.path.join(BASE_DIR, 'mysite', 'static')),
('media', os.path.join(BASE_DIR, 'media')),
)
# print(STATICFILES_DIRS)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
)
# Define place to save media (e.g. pictures for all the projects)
PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media')
MEDIA_URL = '/media/'
models.py:
from django.db import models
from django.conf import settings
# Create your models here.
class AvailableProject(models.Model):
image = models.ImageField(upload_to=settings.MEDIA_ROOT)
我真的经历了流量页面上的每一个堆栈并尝试了以下解决方案,但仍然没有工作......:
<img src="{% static 'media/{{project.image.title}}.jpg' %}" class="img-responsive" alt="">
<img src="{{ project.image.url }}" class="img-responsive" alt="">
我不知道为什么project.image.url没有正确显示相应的图像。
答案 0 :(得分:0)
原因正是Joni Bekenstein所说的。
我更改了这一行,一切正常:
image = models.ImageField(upload_to='uploads/')
然后{{project.image.url}},是正确的网址。