4

Given the nightmare of relative imports in Python, where should I put a simple utils.py file in a Django project that has multiple apps (accessible within the models.py, admin.py, views.py all files of all app directories)?

It seems like there still isn't a good answer for this in 2019, even though Django is by far the most popular framework of the language.

Considering Python 2 will be sunset in January of 2020, please also provide an answer for Python 3.

Alexander Kleinhans
  • 5,950
  • 10
  • 55
  • 111

1 Answers1

3

Actually, this answer addresses this.

Reading this, it was unclear to me as I wasn't sure it was possible for Django to import from a directory or get another nested file to do so, but it appears if you create a common/utils.py file in the root directory (same directory as manage.py), any file within the apps will be able to resolve that import at manage.py's runtime.

You would simply import common.utils and utils.foo() within an app-directories file.

I still don't know how Django makes this happen.

Alexander Kleinhans
  • 5,950
  • 10
  • 55
  • 111