Why does django.utils.importlib.import_module not import the correct app? And how does the variable change?

StackOverflow https://stackoverflow.com/questions/13982442

Question

I was having "models not installed or is abstract" errors that only occur on some machines but not others, and when I delved deeper, I found the problem was the load_app(self, app_name, can_postpone=False) method in django.db.models.loading.py wasn't working as assumed by django.

In def load_app(self, app_name, can_postpone=False) at line 87, I added some print statements. (Original code here: https://github.com/django/django/blob/master/django/db/models/loading.py#L87)

    self.handled[app_name] = None
    self.nesting_level += 1
    app_module = import_module(app_name)
    print "APP--", app_name
    try:
        print "APPNAME-BEGIN", app_name, type(app_name)
        models = import_module('.models', app_name)
        print "APPNAME-END__", app_name
        print "LOADD", str(models), app_name
    except ImportError, e:

You'd think app_name at APPNAME-BEGIN would be same as app_name in APPNAME-END__...

Here is the output:

2012-12-20 15:44:12.526254500 APPNAME-BEGIN users <type 'str'>
2012-12-20 15:44:12.590877500 APPNAME-END__ gradmaker
2012-12-20 15:44:12.590877500 LOADD <module 'gradmaker.models' from '/home/gradcon4/gradcon4/project/gradmaker/models.pyc'> gradmaker

How did app_name change? Why was the wrong module imported? (gradmaker instead of users)

Under what conditions does this occur?

Était-ce utile?

La solution

What's happening was one of the import X lines were raising an ImportError.

i.e import gradmaker.models as gradmaker is incorrect, use from gradmaker import models as gradmaker instead.

The ImportError was caught by one of the functions called by import_module, and skipped.

So the app that this error occurred in didn't get imported correctly.

Once the import line is fixed, all was good.

The variable didn't change, what's happened was the code jumped out of a function due to an error, and made weird output.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top