Is there any way to create decorators.py
file in top-level folder of the project in Django so many applications can use it?
If the file is in top-level dir and I try to import it to myapp/views.py
by:
from ..decorators import student_required, teacher_required
I get an error:
from ..decorators import student_required, teacher_required
ImportError: attempted relative import beyond top-level package
However when importing this way:
from .decorators import student_required, teacher_required
The output is:
from .decorators import student_required, teacher_required
ModuleNotFoundError: No module named 'myapp.decorators'
I need to use this decorators in myapp1, myapp2, myapp3
and I don't want to populate the same file over and over again. Is there any quick workaround for this? How can I point to the decorators.py
properly?
CodePudding user response:
All you need to import it is a path to it. So you could put it in project root and just run:
from decorators import whatever
I'd advise against this because of potential namespacing issues.
Second option is to put it in the django project folder, so you could do:
from <myproject>.decorators import whatever
I usually call my main project config
and then have a core
app alongside it for stuff that is to be used in other apps, so I'd put it there for my setup and run.
from core.decorators import whatever
Or you could just create another module in the root called core
(or anything else) - this is just a directory containing an __init__.py
file, and achieve the same effect.
If it's a big project, you should probably namespace the whole thing too, but that's a different consideration :)
Addendum: If imports in general are problematic, you're either missing an __init__.py
somewhere, or your PYTHONPATH
isn't configured correctly.