Search code examples
djangodjango-templatessorl-thumbnail

The joined path (relative path) is located outside of the base path component (full path)


I am trying to use thumbnail packages to generate thumbnail images from base images. Originally, I had my source images in my static dir, and as the thumbnail packages want to generate them to my media dir, I thought that was the cause of the SuspiciousFileOperation error I was getting.

No problem, I just copied my images to my media dir, which I thought would solve the issue, but no, the issue remains.

From what I can tell, it seems to be a problem with having a relative path vs a full path?

The full error is:

SuspiciousFileOperation at /toys/
The joined path (/media/images/test.jpg) is located outside of the base path component (/home/username/django/first_webapp/my_site/media)

The path /home/username/django/first_webapp/my_site/media/images/test.jpg is valid and test.jpg is a valid jpg image.

The abridged code I am using in my template, with sorl-thumbnail (although I have also tried with easy_thumbnails) is:

{% for instance in prods %}
    <img src=" {% thumbnail instance.image_url 300x300 %} "> 
{% endfor %}

instance.image_url, in this case, is set to /media/images/test.jpg

My media directory settings from my settings.py

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

I am unsure where to begin to troubleshoot this.


Solution

  • I can't really understand how you think the type of the field is not relevant. Of course it is.

    In your case, you have (for some reason) used a TextField to store the path of your image file. TextFields have no special knowledge of media files, and sort-thumbnail just treats the contents as a path component, which it then joins with MEDIA_ROOT. But since your path begins with a leading slash, the result of os.path.join(MEDIA_ROOT, path) is just path; the leading slash means exactly "start from the filesystem root". So the result is a path outside your project, which Django disallows for security reasons.

    A quick fix is to remove the leading slash - as well as the duplicate "media" prefix - and just store "images/test.jpg". But the real fix is to use the appropriate field for the content you are storing, and let that field manage it for you.