Import failing from within a middleware

I am experimenting with a different file tree for a middleware. So, I tried the common structure:

addon
    |- middleware.py
        |-MiddlewareClass

That worked fine. Now I am trying something different.

addon
    |- middleware
        |- __init__.py
        |- module.py
        |- main_module.py
            |-MiddlewareClass

I registered the MiddlewareClass with the following dot notation: addon.middleware.main_module.MiddlewareClass

Django is locating the class but there is one problem. Inside the main_module.py there is an import statement referencing module.py

from module import somemethod

Django chokes on that import statement with an error message: No module named "module" (You know what I mean?)

How do I overcome this? I see that django package handles this well already because the built-in middlewares are inside a “middleware” folder with imports running rife. How did they do it?

I figured it out.

I needed to provide the complete path to the module in the import statement (i.e. in dot notation).

The solution:
from addon.middleware.module import somemethod

:man_facepalming:t5:

1 Like