将图像附加到Django模型中

时间:2012-10-22 21:51:14

标签: python django image model

制作基本的问答网站,并希望将每个问题与图片(管理员已上传)相关联,如果没有相应的图片,请使用默认的“无图片”占位符。

我有两个模型,问答(见下文)。每个问题都需要有一个与之关联的图像,所以我认为最好的方法是将属性ImageField与问题模型相关联。

#models.py
class Question(models.Model):
    title = models.CharField(max_length = 500)
    picture = models.ImageField(height_field = '250',
                                width_field = '200',
                                upload_to = 'images')
    def __unicode__(self):
        return self.title

当我运行服务器时,告诉我下载Python Imaging Library,当我收到错误时(不同的问题)。

退一步,在Django中将图像添加到模型的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

忘掉PIL ......

使用位置URL数据库条目。而不是使用ImageField(),使用

picturepath = models.CharField(255)

包含指向图像静态位置的URL。

所以如果STATIC_URL =“http://127.0.0.1/static/” 和picturepath =“images / poots.png”

然后,在视图中传递该信息,并在模板中使用它:

<img src="{{ STATIC_URL }}{{ question.picturepath }}">

将提供

<img src="http://127.0.0.1/static/images/poots.png">