[英]Attach an image into a Django Model
Making a basic Q&A site and want to associate each question with an image (admin uploaded) and if there is no respective image, puts it with a default "No Image" placeholder. 制作一个基本的Q&A网站,并希望将每个问题与一张图片相关联(由管理员上传),如果没有相应的图片,则将其与默认的“无图片”占位符放在一起。
I have two models, Question and Answer (see below). 我有两个模型,问题和答案(见下文)。 Each question needs to have an image associated with it, so I thought the best way was to attach attribute ImageField with the Question model.
每个问题都需要有一个与之关联的图像,所以我认为最好的方法是将属性ImageField与Question模型一起附加。
#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
When I runserver though, tells me to download Python Imaging Library, and when I do get an error (different problem). 但是,当我运行服务器时,告诉我下载Python Imaging Library,并且确实出现错误(不同的问题)。
Taking a step back, what is the best way to add an image to a model in Django? 退一步,在Django中向模型添加图像的最佳方法是什么?
Forget PIL... 忘了PIL ...
Use a location URL DB entry. 使用位置URL数据库条目。 Instead of having an ImageField(), use
代替使用ImageField(),使用
picturepath = models.CharField(255)
that contains a URL to the static location of the image. 包含指向图片静态位置的URL。
so if STATIC_URL = "http://127.0.0.1/static/" and picturepath = "images/poots.png" 因此,如果STATIC_URL =“ http://127.0.0.1/static/”并且picturepath =“ images / poots.png”
Then, pass that information along in the view, and use this in the template: 然后,在视图中传递该信息,并在模板中使用它:
<img src="{{ STATIC_URL }}{{ question.picturepath }}">
will provide 会提供
<img src="http://127.0.0.1/static/images/poots.png">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.