python - FileNotFoundError - [Errno 2] 没有这样的文件或目录:'/static/background.jpg' - Django
问题描述
我在 Python、Django 框架中编写了以下代码:
class ImageGenerator:
def __init__(self, tip):
self.tip = tip
def remove_transparency(self, im, bg_colour=(250, 250, 250)):
if im.mode in ('RGBA', 'LA') or (im.mode == 'P' and 'transparency' in im.info):
alpha = im.convert('RGBA').split()[-1]
bg = Image.new("RGBA", im.size, bg_colour + (255,))
bg.paste(im, mask=alpha)
return bg
else:
return im
def generate(self):
print('Triggered')
border = 3
home_url = self.tip.fixture.home.image_url
away_url = self.tip.fixture.away.image_url
home_name = self.tip.fixture.home.name
away_name = self.tip.fixture.away.name
response = requests.get(home_url)
home = self.remove_transparency(Image.open(BytesIO(response.content)))
home_w, home_h = home.size
response = requests.get(away_url)
away = self.remove_transparency(Image.open(BytesIO(response.content)))
away_w, away_h = away.size
background_image = Image.open('/static/background.jpg', 'r')
当我执行此代码时,我收到以下错误:
FileNotFoundError at /fixtures/view/54848
[Errno 2] No such file or directory: '/static/background.jpg'
Request Method: POST
Request URL: http://127.0.0.1:8000/fixtures/view/54848
Django Version: 3.0.3
Exception Type: FileNotFoundError
Exception Value:
[Errno 2] No such file or directory: '/static/background.jpg'
Exception Location: /home/sander/.local/lib/python3.6/site-packages/PIL/Image.py in open, line 2809
Python Executable: /usr/bin/python3
Python Version: 3.6.9
Python Path:
['/home/sander/git/football',
'/usr/lib/python36.zip',
'/usr/lib/python3.6',
'/usr/lib/python3.6/lib-dynload',
'/home/sander/.local/lib/python3.6/site-packages',
'/usr/local/lib/python3.6/dist-packages',
'/usr/lib/python3/dist-packages']
Server time: Fri, 28 Feb 2020 18:56:54 +0000
我在 django 设置文件中定义了以下变量:
STATIC_URL = "/static/"
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static')
我尝试static
使用from django.templatetags.static import static
. 这会产生相同的错误。该collectstatic
命令也不能解决问题。
有谁知道解决这个问题?
解决方案
我认为您的代码在线中断:
background_image = Image.open('/static/background.jpg', 'r')
由于您在路径的开头使用斜杠,Python 会尝试将此文件作为文件系统中的绝对路径查找。确保它在您在那里编写时存在。
您可以尝试使用完整的绝对路径,但最佳做法是使用相对路径。
推荐阅读
- spring-boot - How to convert plain java main method program on docker
- xml - 如何重新分发 MSXML 库?
- java - 为什么我在更换 Arial Narrow 时会得到额外的符号?
- ansible - 使用 Ansible 按第二个列表的特定顺序映射 Debian 软件包列表
- javascript - 我无法正确重新缩放
- rspec - 在 rspec 中获取安全的随机值
- istio - 如何使用 istio 在网格中绕过 jwt 策略
- android - GoogleVR 库不支持 Playstore 的 64 位要求
- pandas - 分层 Kfold
- java - 如何将数组元素反向分配到另一个数组中?我是初学者