我在完成how to tango with django教程后构建我的第一个网站,我正在尝试使用模板语言添加一些图像,但我只得到一些蓝色的问号图标
models.py
from django.db import models
class Galery(models.Model):
title = models.CharField(max_length = 120)
def __unicode__(self):
return self.title
class Image(models.Model):
galery = models.ForeignKey(Galery)
name = models.CharField(max_length = 50, unique = True)
picture = models.ImageField(upload_to='media')
description = models.CharField(max_length = 500)
materials = models.CharField(max_length = 150)
def __unicode__(self):
return self.name
galery.html
{%extends 'home/base.html'%}
{%load static%}
{%block body%}
<div class="col-lg-12">
<h1 class="page-header">My Projects</h1>
</div>
{%if image%}
{%for n in image%}
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="">
<img class="img-responsive" src="{% static 'media/{{n.image.url}}' %}">
</a>
</div>
{%endfor%}
{%endif%}
{%endblock%}
settings.py(part)
PROJECT_PATH = os.path.join(SETTINGS_DIR, os.pardir)
MEDIA_ROOT = os.path.join(PROJECT_PATH,'media')
TEMPLATE_DIRS = (
TEMPLATE_PATH,
)
STATICFILES_DIRS = (
STATIC_PATH,
)
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
编辑:忘了提到我从管理员上传了一些图片
EDIT2:在我的urls.py中我有
if settings.DEBUG:
urlpatterns += patterns(
'django.views.static',
(r'media/(?P<path>.*)',
'serve',
{'document_root': settings.MEDIA_ROOT}), )
答案 0 :(得分:0)
默认情况下,Django不提供用户上传的图像。通过添加以下URL conf来设置它:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
# ... the rest of your URLconf goes here ...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
这仅适用于开发。在生产中,您需要以更具可扩展性的方式提供文件(直接来自HTTP服务器,甚至更好,来自文件存储服务,如S3或CDN。)