'Django's static() function to retrieve static file gives no such file -error
I'm doing a project with Django with the following structure:
/project
/cv
/static
/configuration
configuration.json
So a project with one app in it and a config.json file in the static folder.
My settings.py (the most important settings for this):
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"cv",
]
STATIC_URL = "/static/"
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(BASE_DIR, "cv/static")
In my view I use the static() function to retrieve the static file
def index(request):
file_path = static("configuration/configuration.json")
with open(file_path) as f:
configuration = json.loads(f.read())
return render(request, "index.html", configuration)
But It keeps giving me the error:
No such file or directory: '/static/configuration/configuration.json'
I can fix it by explicitly parsing the path string to the index function:
def index(request):
file_path = "./cv/static/configuration/configuration.json"
with open(file_path) as f:
configuration = json.loads(f.read())
return render(request, "index.html", configuration)
But how do I do it with the static() function? The static() function uses the static_url variable, but no matter how I adjust it, it keeps giving me a similar error.
Anyone an idea what I'm doing wrong here?
Solution 1:[1]
The static()
function is going to return the URL that the file can be accessed at, you don't need that, you need to get the path to the file on the filesystem.
Join settings.STATIC_ROOT
and the file to get the path to the file on the filesystem
def index(request):
file_path = os.path.join(settings.STATIC_ROOT, "configuration/configuration.json")
with open(file_path) as f:
configuration = json.loads(f.read())
return render(request, "index.html", configuration)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Iain Shelvington |