在我的模板中获得了此标记代码,以将静态文件夹中的一些图像转换为 base64:
标签.py:
import datetime
import base64
from django import template
from django.conf import settings
from django.contrib.staticfiles.templatetags.staticfiles import static
from django.contrib.staticfiles.finders import find as find_static_file
@register.simple_tag
def encode_static(path, encodign='base64', file_type='image'):
"""
to use like this:
<img src="{% encode_static 'path/to/img.png' %}" />
"""
try:
file_path = find_static_file(path)
ext = file_path.split('.')[-1]
file_str = get_file_data(file_path).decode('utf-8')
return "data:{0}/{1};{2}, {3}".format(file_type, ext, encodign, file_str)
except IOError:
return ''
def get_file_data(file_path):
""" Return base 64 archivo """
with open(file_path, 'rb') as f:
data = base64.b64encode(f.read())
f.close()
return data
这是我的项目文件夹结构:
MyProject
MyProject
Lib
Static
MyApp
Images
Header.png
我在 base.py 中的静态目录配置:
STATIC_URL = '/Static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "Lib/Static"),
]
但是当我像这样从我的模板中调用标签时:
<img src="{% encode_static '/MyApp/Images/Header.png' %}" />
我不断收到此错误:
The joined path (/MyApp/Images/Header.png) is located outside of the
base path component (MyProject/MyProject/Lib/Static)
没有任何意义,它确实在那个位置内,知道为什么会这样吗?