Got this tag code to convert some images in static folder to base64 in my templates:
Tags.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
This is my project folder structure:
MyProject
MyProject
Lib
Static
MyApp
Images
Header.png
And my static dirs conf in base.py :
STATIC_URL = '/Static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "Lib/Static"),
]
But when I call the tag from my template like this:
<img src="{% encode_static '/MyApp/Images/Header.png' %}" />
I keep getting this error:
The joined path (/MyApp/Images/Header.png) is located outside of the
base path component (MyProject/MyProject/Lib/Static)
Doesn't make any sense, it's indeed inside that location, any idea why is this happening?