如何在模板中显示图像?
我尝试这样的事情(但不起作用):
这是我的模特:
from django.db import models
class Photo(models.Model):
title = models.CharField(max_length=255)
img = models.ImageField(upload_to="media/galery")
class Meta:
verbose_name = "Galery"
verbose_name_plural = "Galery"
def __unicode__(self):
return self.title
views.py
from django.shortcuts import render_to_response
from django.template import RequestContext
from kolejny.galery.models import Photo
def photo(request):
photos = Photo.objects.all()
return render_to_response('photo.html', {'photos' : photos}, context_instance=RequestContext(request))
photo.html
{% for p in photos %}
<img src="{{ p.img.url }}"/>
{% endfor %}
urls.py
urlpatterns = patterns('',
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
url(r'^photo/$', 'galery.views.photo'),
url(r'^site_media/(.*)$', 'django.views.static.serve', {'document_root' : os.path.join(os.path.dirname(__file__), 'site_media')}),
)
settings.py:
MEDIA_ROOT = ''
MEDIA_URL = ''
STATIC_ROOT = ''
STATIC_URL = '/static/'
如何解决?
答案 0 :(得分:4)
将MEDIA_ROOT变量设置为指向实际图像所在的文件夹,如:
MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'site_media')
和urls.py中指向同一文件夹的行:
url(r'^site_media/(.*)$', 'django.views.static.serve', {'document_root' : settings.MEDIA_ROOT}),
和MEDIA_URL:
MEDIA_URL = '/site_media/'