首页 > 解决方案 > Django 错误:无法使用 ImageField,因为未安装 Pillow

问题描述

我目前正在学习如何使用 Django 开发 Web 服务。当我学习关于 Udemy 的在线课程时,我在 models.py 中使用 ImageField 时遇到了问题。我的问题是,当我执行 runserver 命令时,Django 显示以下错误,尽管我很确定库 Pillow 已安装。

在models.py中,我有以下代码:

from django.db import models
from django.contrib.auth.models import User 
class UserProfileInfo(models.Model):
    user = models.OneToOneField(User, on_delete=models.PROTECT) 
    portfolio = models.URLField(blank=True)
    picture = models.ImageField(upload_to="profile_pics")
    def __str__(self):
     return user.self.username

当我运行服务器时,我收到以下错误: python manage.py runserver Performing system checks...

Unhandled exception in thread started by <function check_errors<locals>.wrapper at 0x10407b6a8>
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run
self.check(display_num_errors=True)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site- 
packages/django/core/management/base.py", line 410, in check
 raise SystemCheckError(msg)
django.core.management.base.SystemCheckError: SystemCheckError: System check 
 identified some issues:

ERRORS:
first_app.UserProfileInfo.picture: (fields.E210) Cannot use ImageField because 
Pillow is not installed.
HINT: Get Pillow at https://pypi.python.org/pypi/Pillow or run command "pip
install Pillow".

System check identified 1 issue (0 silenced).

因此,按照以下消息,我使用此处介绍的方法检查了已安装的模块:如何获取本地安装的 Python 模块的列表?. 以下代码在与 manage.py 相同目录中的文件中运行。我正在使用 Pycharm 来使用虚拟环境,所以我假设我使用的环境与运行服务器时 Django 项目使用的环境相同。

作为上述方法的结果,我可以看到 Pillow 已安装,如下所示:

['argon2==0.1.10', 'bcrypt==3.1.4', 'cffi==1.11.5', 'django==2.0.5', 'faker==0.8.15', 'olefile== 0.45.1'、'pillow==5.0.0'、'pip==9.0.1'、'pycparser==2.18'、'python-dateutil==2.7.3'、'pytz==2018.4'、'setuptools ==28.8.0','六==1.11.0','text-unidecode==1.2']

我该如何解决这个问题?或者,有没有其他方法可以在没有 Pillow 的情况下在 Django 中使用图像?

标签: pythondjangodjango-modelspillow

解决方案


我在 docker 容器中遇到了这个问题。如果没有 jpeg 和 zlib 头文件和库支持,Pillow 将无法安装,所以我在构建中添加了 zlib-dev 和 jpeg-dev,然后在安装 Pillow 后将它们删除。当然 Pillow 拒绝导入,因为缺少 libjpeg 和朋友。解决方案是重新添加相关的(非开发)包,一切都开始按预期工作。


推荐阅读