bong0s_guy01
bong0s_guy01

Reputation: 21

DJANGO: This backend doesn't support absolute paths

I´m trying to set a path for some json files I have to open with python open() method. Reading documentation I noticed that path method from class Storage in django.core.files.storage must be overrided but I don't know how to override it since I don't know how to store this path.

My files are this way

App
--index_backend
----json
-------some_json.json
----index.py
--views.py
manage.py

I'm quite new on Django, so if you need to see some more code, please tell me to upload as much as needed.

Update What I want to achieve is to call a function when a button is clickled, this button sends a request to http://127.0.0.1:8000/App/getValues in order to run a python function which calls another python function in index.py. Inside index.py some_json.json is opened, but when running getValues, it raises FileNotFoundError at /App/getValues/, because its looking for some_json.json in /App/getValues/ instead of /App/index_backend/json/

Upvotes: 2

Views: 943

Answers (4)

Bob Square
Bob Square

Reputation: 1

For those using bucket storage - AWS or similar If you are using media - construct your file path with:

from django.core.files.storage import get_storage_class

// Double braces are needed here

media_storage = get_storage_class()()

file_path = media_storage.url(name=fileobj.file.name)

Upvotes: 0

bong0s_guy01
bong0s_guy01

Reputation: 21

None of above worked, after a lot of searching, this worked for me.

First, added MEDIA ROOT because I needed these JSON files to be dynamic

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

Then, on index_backend/index.py imported default_storage

from django.core.files.storage import default_storage
with default_storage.open('some_json.json', "r") as some_json_file:
      doSomethingJSONGLYCool(some_json_file)

It is important to set media folder as

App
--index_backend
----index.py
--media
---path/to/json
--views.py
manage.py

Upvotes: 0

NikzJon
NikzJon

Reputation: 954

Here is a method you can use inside index if you are using Django 3.1+

from django.conf import settings

BASE_DIR = settings.BASE_DIR

JSON_FILE = BASE_DIR / 'App/index_backend/json/some_json.json'

Upvotes: 0

François Fournier
François Fournier

Reputation: 316

in your index.py file:

import json
import os

this_file = os.path.realpath(__file__)
this_folder = os.path.dirname(this_file)
path_to_json = os.path.join(this_folder, 'json', 'some_json.json')

with open(path_to_json) as f:
    data = json.load(f)

print(data)

Upvotes: 0

Related Questions