Django用媒体目录显示ImageField [英] Django Display ImageField With Media Dir

查看:69
本文介绍了Django用媒体目录显示ImageField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django 1.9.3.我正在尝试显示某个用户上传的媒体文件(例如imageFields).

I am using Django 1.9.3. I am trying to display media files uploaded by say a user (e.g. 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:

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:

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) 

我实际上已经遍历了流页面上的每个堆栈,并尝试了以下解决方案,但仍然无法正常工作...:

I have literally went through every single stack over flow page on this and tried the following solutions, but still has not worked...:

<img src="{% static 'media/{{project.image.title}}.jpg' %}" class="img-responsive" alt="">
<img src="{{ project.image.url }}" class="img-responsive" alt="">

我不知道为什么project.image.url没有正确显示相应的图像.

I don't know why the project.image.url is not showing the corresponding image correctly.

推荐答案

原因恰恰是乔尼·贝肯斯坦(Joni Bekenstein)所说的.

The reason was exactly what Joni Bekenstein said.

我更改了这一行,一切正常:

I changed this one line and everything worked:

image = models.ImageField(upload_to='uploads/')

然后{{project.image.url}}是正确的URL.

Then {{ project.image.url }}, was the correct url.

这篇关于Django用媒体目录显示ImageField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆