0

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?

martineau
  • 119,623
  • 25
  • 170
  • 301
jsanchezs
  • 1,992
  • 3
  • 25
  • 51
  • 1
    maybe you should use relative path without `/` at the beginning - `encode_static 'MyApp/Images/Header.png'` . Using with `/` it may treats it as absolute path which is not in your project. – furas Jun 10 '20 at 17:47
  • Put it as answer to check it , indeed that was the problem, thanks !!! – jsanchezs Jun 10 '20 at 19:12

1 Answers1

1

You should use relative path without / at the beginning

encode_static 'MyApp/Images/Header.png' 

Using with / it treats it as absolute path which is not in your project.

furas
  • 134,197
  • 12
  • 106
  • 148