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
  •  | 
  •  

質問

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.)

役に立ちましたか?

解決

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()
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top