1

如何在模板中显示图像?

我尝试这样的事情(但不起作用):

这是我的模型:

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

视图.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))

照片.html

{% for p in photos  %}
<img src="{{ p.img.url }}"/>
{% endfor %}

网址.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')}),
)

设置.py:

MEDIA_ROOT = ''
MEDIA_URL = ''
STATIC_ROOT = ''
STATIC_URL = '/static/'

如何解决?

4

1 回答 1

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/'
于 2012-09-19T16:39:07.250 回答