Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import error on django models.py

Tags:

python

django

I wrote this funcion on a utils.py located on the app direcroty:

from bm.bmApp.models import Client

def get_client(user):
    try:
        client = Client.objects.get(username=user.username)
    except Client.DoesNotExist:
        print "User Does not Exist"
        return None
    else:       
        return client

def to_safe_uppercase(string):
    if string is None:
        return ''
    return string.upper()

Then when i use the function to_safe_uppercase on my models.py file, by importing it in this way:

from bm.bmApp.utils import to_safe_uppercase 

I got the python error:

     from bm.bmApp.utils import to_safe_uppercase
ImportError: cannot import name to_safe_uppercase

I got the solution for this problem when i change the import statement for:

from bm.bmApp.utils import *

But i can't understand why is this, why when i import the specific function i got the error?

like image 383
alacret Avatar asked Apr 18 '12 15:04

alacret


2 Answers

You are doing what is known as a Circular import.

models.py:

from bm.bmApp.utils import to_safe_uppercase

utils.py:

from bm.bmApp.models import Client

Now when you do import bm.bmApp.models The interpreter does the following:

  1. models.py - Line 1: try to import bm.bmApp.utils
  2. utils.py - Line 1: try to import bm.bmApp.models
  3. models.py - Line 1: try to import bm.bmApp.utils
  4. utils.py - Line 1: try to import bm.bmApp.models
  5. ...

The easiest solution is to move the import inside the function:

utils.py:

def get_client(user):
    from bm.bmApp.models import Client
    try:
        client = Client.objects.get(username=user.username)
    except Client.DoesNotExist:
        print "User Does not Exist"
        return None
    else:       
        return client

def to_safe_uppercase(string):
    if string is None:
        return ''
    return string.upper()
like image 187
Jiaaro Avatar answered Sep 20 '22 11:09

Jiaaro


You are creating a circular import.

utils.py
from bm.bmApp.models import Client
# Rest of the file...

models.py
from bm.bmApp.utils import to_safe_uppercase
# Rest of the file...

I would suggest your refactor your code so that you don't have a circular dependency (i.e. utils should not need to import models.py or vice versa).

like image 30
Mark Lavin Avatar answered Sep 20 '22 11:09

Mark Lavin