文件结构
\project_structure
-app
\project
-settings.py
-...
\picture
-panda.jpg
Models.py
class Goods(models.Model):
pic = models.ImageField(upload_to='picture')
我上传了一个图片文件到picture/panda.jpg
那么,怎么在前端显示呢?
我写的:
<p>{{each.pic}}</p>
<img src='{{ each.pic.url }}' />
浏览器解释:
picture/panda.jpg
<img src='picture/panda.jpg' />
图片链接到了http://localhost:8000/my_sell...不能显示。
怎么解决?
Django application looks for static files. By default, it will go to
static
文件夹去找,如果在settings.py中配置了STATICFILES_DIRS
in the corresponding app directory, and it will also search here.And your picture directory is picture/... not in the static folder under the app directory. So additional configuration is required in
STATICFILES_DIRS
.Then when accessing, pass
{% load staticfiles %}
<img src='{{ each.pic.url }}' />
If you configured STATICFILES_DIRS and still can't find the image, check the error message specifically.
First of all, make sure you configure the processing of static files in django. If it is the development stage, you need to configure the two options STATIC and MEDIA. If it is a production environment, it is best to use a web server to host static files. For details, you can check django in the development environment. It works after downloading both static and media folders
<img src='/media/{{ each.pic.url }}' />