Get absolute path of django app

后端 未结 6 2028
一整个雨季
一整个雨季 2021-02-03 20:09

I am writing a unit test that needs to access an image file that I put in \"fixtures\" directory right under my django app directory. I want to open up this image file in my tes

6条回答
  •  余生分开走
    2021-02-03 20:52

    So the accepted answer usually works fine. However, for

    • namespace packages with multiple paths, or
    • apps which explicitly configure their paths in the config,

    their intended path may not agree with the __file__ attribute of the module.

    Django (1.7+) provides the AppConfig.path attribute - which I think is clearer even in simple cases, and which covers these edge cases too.

    The application docs tell you how to get the AppConfig object. So to get AppConfig and print the path from it:

    from django.apps import apps
    print(apps.get_app_config('app_label').path)
    

    Edit: Altered example for how to use get_app_config to remove dots, which seems to have been confusing. Here are the docs for reference.

提交回复
热议问题