Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Location for app-wide utils file in a Django project

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.

like image 953
Alexander Kleinhans Avatar asked Oct 16 '25 13:10

Alexander Kleinhans


1 Answers

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.

like image 145
Alexander Kleinhans Avatar answered Oct 18 '25 11:10

Alexander Kleinhans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!