问题是我得到了破碎的图像类型。我的代码如下:
在settings.py中我有
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SETTINGS_DIR = os.path.dirname(__file__)
PROJECT_PATH = os.path.join(SETTINGS_DIR, os.pardir)
PROJECT_PATH = os.path.abspath(PROJECT_PATH)
TEMPLATE_DIRS = [os.path.join(PROJECT_PATH, 'templates')]
MEDIA_ROOT = '/home/username/work_station/project1/media/static/pic'
MEDIA_URL = '/media/'
PROJECT_ROOT = os.path.join(os.path.dirname(__file__), '..')
SITE_ROOT = PROJECT_ROOT
STATIC_ROOT = os.path.join(SITE_ROOT, 'static')
我的models.py
class Image(models.Model):
post = models.ForeignKey(Post)
image = models.ImageField(upload_to='static/pic/', default = None)
description = models.CharField(max_length=100)
def __unicode__(self):
我的观点
class IndexListView(ListView):
template_name = "dashboard.html"
context_object_name = 'latest_pictures'
def get_queryset(self):
return Image.objects.all()
return str(self.image)
我的模板:dashboard.html
{% for latest in latest_pictures %}
{% load staticfiles %}
<div><img src="{{ MEDIA_URL }}{{ latest.image }}"></div>
{% endfor %}
答案 0 :(得分:1)
实际上,您的MEDIA_ROOT
应为
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
和图像文件不是静态文件,它们是媒体文件。所以...
{% for latest in latest_pictures %}
<div><img src="{{ latest.image.url }}"></div>
{% endfor %}
应该足够好。
和btw,upload_to
是media
文件夹下的目的地。 upload_to='static/pic/'
是一种误导性的名字..