Visitor : 645

Read Comments

Relative and Absolute import for beginners

Django Migration


First things first:

When From or Import is used we are trying to refer python code available in different file without having to copy the same set of code to your file.

FROM : From will import the code into the current namespace so that you can use the code without refering to the module.

Note : url is used with the same module name

from django.conf.urls import url
url(r'^$', app.views.home, name='home'),

 

IMPORT : When import is used python module / code is imported to its own namespace and the entire path should be used when the module is referred.

import django.contrib.auth.views
url(r'^login/$',
        django.contrib.auth.views.LoginView.as_view(),
        {...}

So when import is used make sure the full path is being refered to.

 

Beginners Pitfall

Scenario 1 : Multiple FROM with the same object name

Incorrect 
from app import views
from app2 import views

Correct
import app
import app2

If the object to be used from different modules have same name always import , so that python can understand that they are codes in different modules(because import is always refered with full path)




Add Comments