python - Django 图片连接失效
ringa_lee
ringa_lee 2017-04-18 10:01:46
0
3
368

文件结构

\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...不能显示。

怎么解决?

ringa_lee
ringa_lee

ringa_lee

reply all(3)
阿神

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.

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "picture"),
)

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 }}' />

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!