Django and Heroku - How do I get an absolute path to my static files in production?

StackOverflow https://stackoverflow.com/questions/22159887

  •  19-10-2022
  •  | 
  •  

Question

In my settings.py file:

import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

How can I get an absolute local path to the static root from one of my view methods? (Not the template.)

Was it helpful?

Solution

You can use the request.build_absolute_uri() built-in method. Pass it the relative URL (/static/) and it will return the absolute one.

UPDATE

To open/read the file in your view:

cool = open(os.path.join(settings.STATIC_ROOT, 'cool_styles.css', 'rb').read()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top