'import views vs from . import views

I am new to Python and Django, I have an app directory called calc and inside it there are two files:

  1. views.py
  2. urls.py

In urls.py, if I type in import views the server generates an error, however if I type from . import views everything works fine. Could someone explain why? I thought since the two py files are in the same directly, the import statement should match the views.py



Solution 1:[1]

Since your files are in your calc module, you have to use import calc.views, not import views.

You can then refer to some view function some_func as calc.views.some_func.

Or you could do import calc.views as views, and then you can refer to the function as views.some_func, the same as when you use from . import views.

The reason you have to include the calc prefix with import calc.views is because that is considered an "absolute import", and calc itself is not in your $PYTHONPATH -- its parent directory is.

In any case, you are probably better off sticking with from . import views (which is referred to as a "relative import").

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 taherh