highpost
highpost

Reputation: 1323

manage.py shell and relative imports

I'm trying to load the following Python file with "manage.py shell". The manage.py script is in a parent directory and I'm using execfile('forms.py') from the directory containing the script.

from django.forms import ModelForm
from .models import Profile

class ProfileSearchForm(ModelForm):
    class Meta:
        model = Profile
        fields = ['name']

This fails because of the explicit relative import:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "forms.py", line 2, in <module>
    from    .models         import    Profile
ImportError: No module named models

but if I switch to implicit relative import, it works:

from django.forms import ModelForm
from apps.myprofile.models import Profile

class ProfileSearchForm(ModelForm):
    class Meta:
        model = Profile
        fields = ['name']

My problem is that I thought that explicit relative imports are a good thing (see Two Scoops), and I still think they are.

But now I need a workaround with manage.py.

Upvotes: 3

Views: 1863

Answers (1)

defool
defool

Reputation: 301

you need to change the current directory before the relative import in python shell. So this may works:

import os
os.chdir('apps/')
from django.forms import ModelForm
from .models import Profile

Upvotes: 2

Related Questions