即使路径正确,Django object.image.url也不显示

时间:2017-02-20 01:37:03

标签: python django

我有通过django admin上传的图片,但它们没有显示。奇怪的是,我有另一个项目与EXACT相同的代码,它的工作原理。 object.image.url和我的其他项目一样输出/media/media/image.jpg。但是这个项目没有显示图像。如果我从静态文件夹中放入图像或者我对图像进行硬编码,则可以正常工作。问题是当我尝试从管理员上传的图像时它不起作用。我在settings.py文件中遗漏了什么?还是在任何地方?

Models.py:

from django.db import models

# Create your models here.
class Connect(models.Model):
title = models.CharField(max_length=70)
short_description = models.TextField(null=True, blank=True)
description = models.TextField()
image = models.ImageField(upload_to='media', blank=True, null=True)

def __str__(self):
    return self.title

views.py:

def index(request):
about = About.objects.all()
staff = Staffmembers.objects.all()
ministries = Ministries.objects.all()
connect = Connect.objects.all()
context = {
    'template': 'home',
    'connect': connect,
    'about': about,
    'staff': staff,
    'ministries': ministries,
    }
return render(request,'home/index.html', context)

模板(index.html的):

<div class="connect-wrapper row">
        <h1 class="title connect-title">Connect</h1>
        {% for object in connect %}
    <div class="home-div connect-div col-md-4">
        <h4>{{ object.title }}</h4>
        <p>{{ object.short_description }}</p>
        {% if object.image %}
        <img class="connect-image-home" src="{{object.image.url}}" alt="connect">
        <p>{{object.image.url}}</p> //sanity check
        {% endif %}
    </div>
    {% endfor %}
</div>

settings.py:

STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')

urls.py:

from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include('home.urls'), name="home"),
]

1 个答案:

答案 0 :(得分:0)

我相信您需要将媒体网址添加到您的urls.py.类似的东西:

string one = "12345678901234567890";
string other = string.Join("",one .Take(15));