Home > Mobile >  import views vs from . import views
import views vs from . import views

Time:05-24

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

CodePudding user response:

The answer is really simple. By default if you import everything, you are importing it from standard pythonish library. If you expand it to from everything.something import anything it checks the path starting with app everything modules. If not successful, it also tries to look for global.

In your case it looks inside same folder (starting .) for module views which isn't global package, so it cannot be achieved by simple import views.

CodePudding user response:

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").

  • Related