Question: What is the correct way of doing Django imports ?

Question

What is the correct way of doing Django imports ?

Answers 1
Added at 2017-01-05 13:01
Tags
Question

I would like to understand if the there is a correct and accepted way of handling imports in Django?

I use following patterns >

# import views from Django app called xxx to urls.py in the same app
from . import views

What I see been used in many tutorials and blogs >

# import views from Django app called xxx to urls.py in the same app
from xxx import views

Similarly I use >

# import YYY and XXX from xxx.models to xxx.serializers.py
from .models import YYY, XXX

What I see been used for example in Django-Rest-Framework tutorial is >

# import YYY and XXX from xxx.models to xxx.serializers.py
from xxx.models import XXX, YYY

Doing imports in the way shown in tutorials does not work in my Django apps. Am I doing something wrong? I picked my way from Django documentation. I am using Django 1.10 with Python3.5

Answers to

What is the correct way of doing Django imports ?

nr: #1 dodano: 2017-01-05 17:01

Say you have a Django Project which looks like this: 2 apps named app_1 and app_2

mysite/
    manage.py
    app_1/
        __init__.py
        models.py
        views.py
    app_2/
        __init__.py
        models.py
        views.py
    mysite/
        __init__.py
        settings.py
        urls.py
        wsgi.py

Now to run this application you will use this command.

mysite> python manage.py runserver

Here you are running the command from mysite parent folder/directory.

Now in a python app_1 views code say you are import app_2 model (which you should not have to do if your code is well structured). But to make that import you will have to do the complete namespace.

example:

from app_2.models import XXX

On the other hand if you wanted to import model from within the same app app_1 you could have used

from .models import YYY

but if you are running the program using mysite> python manage.py runserver command you should be able to import the same module with the full namespace path also.

from app_1.models import YYY

NOTE: A good way to code is always be explicit. Hence you would notice these are more commonly prescribed.

# import views from Django app called xxx to urls.py in the same app
from xxx import views

# import YYY and XXX from xxx.models to xxx.serializers.py
from xxx.models import XXX, YYY
Source Show
◀ Wstecz