Yannick
Yannick

Reputation: 3653

Django - Error importing module context_processors

Newbie question for you.

I am trying to create my first custom context processor

my settings.py

TEMPLATE_CONTEXT_PROCESSORS = (
    'mmaprophet.context_processors.seasons.active'

)

My project directory is called "mmaprophet", so I created a folder called "context_processors", and in it, I created a file called "seasons.py". That file contains the function active defined above.

my seasons.py

from seasons.models import Season


def active(request):
    '''
    A context processor to add the "active season" to the current Context
    '''

    active_season = Season.objects.get(active=True)

    return {'active_season': active_season}

But then I get this error:

    ImproperlyConfigured at /
Error importing module mmaprophet.context_processors.seasons: "No module named models"
Request Method: GET
Request URL:    http://127.0.0.1:8000/
Django Version: 1.6.2
Exception Type: ImproperlyConfigured
Exception Value:    
Error importing module mmaprophet.context_processors.seasons: "No module named models"
Exception Location: /home/ymorin007/workspace/sites/mmaprophet.com/src/mmaprophet/context_processors/seasons.py in <module>, line 2
Python Executable:  /home/ymorin007/.virtualenvs/mmaprophet/bin/python
Python Version: 2.7.6
Python Path:    
['/home/ymorin007/workspace/sites/mmaprophet.com/src',
 '/home/ymorin007/workspace/sites/mmaprophet.com/src',
 '/home/ymorin007/.virtualenvs/mmaprophet/lib/python2.7',
 '/home/ymorin007/.virtualenvs/mmaprophet/lib/python2.7/plat-x86_64-linux-gnu',
 '/home/ymorin007/.virtualenvs/mmaprophet/lib/python2.7/lib-tk',
 '/home/ymorin007/.virtualenvs/mmaprophet/lib/python2.7/lib-old',
 '/home/ymorin007/.virtualenvs/mmaprophet/lib/python2.7/lib-dynload',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-x86_64-linux-gnu',
 '/usr/lib/python2.7/lib-tk',
 '/home/ymorin007/.virtualenvs/mmaprophet/local/lib/python2.7/site-packages']
Server time:    Thu, 22 May 2014 13:13:31 -0400

Upvotes: 0

Views: 370

Answers (2)

Yannick
Yannick

Reputation: 3653

The issue was because I used the same name as my app "seasons" as the file inside my context_processors folder "seasons.py"

Now it works perfectly.

Upvotes: 2

Maxime Lorant
Maxime Lorant

Reputation: 36141

You need to add an empty __init__.py file to declare the folder as a Python module. You can import from files which are in folder with __init__.py or from the current folder only.

You may know it, but as a reminder, from the documentation:

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.


Your Python path does not include the root of your project also, you should add it to be able to import things from there.

Upvotes: 1

Related Questions