droidfish
droidfish

Reputation: 301

Python error in virtuaenv

I have a script, which should run once per day by crontab. That works fine on my desktop. But when I try to run it on a virtualenv on my RPi, I get this error:

Traceback (most recent call last):
  File "mailalert.py", line 7, in <module>
    from django.contrib.auth.models import User
  File "/usr/local/lib/python2.7/dist-packages/Django-1.5.4-py2.7.egg/django/contrib/auth/__init__.py", line 5, in <module>
    from django.middleware.csrf import rotate_token
  File "/usr/local/lib/python2.7/dist-packages/Django-1.5.4-py2.7.egg/django/middleware/csrf.py", line 16, in <module>
    from django.utils.cache import patch_vary_headers
  File "/usr/local/lib/python2.7/dist-packages/Django-1.5.4-py2.7.egg/django/utils/cache.py", line 26, in <module>
    from django.core.cache import get_cache
  File "/usr/local/lib/python2.7/dist-packages/Django-1.5.4-py2.7.egg/django/core/cache/__init__.py", line 70, in <module>
    if DEFAULT_CACHE_ALIAS not in settings.CACHES:
  File "/usr/local/lib/python2.7/dist-packages/Django-1.5.4-py2.7.egg/django/conf/__init__.py", line 53, in __getattr__
    self._setup(name)
  File "/usr/local/lib/python2.7/dist-packages/Django-1.5.4-py2.7.egg/django/conf/__init__.py", line 46, in _setup
    % (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting CACHES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

It looks like I cant use:

from django.contrib.auth.models import User

What is the problem?

Upvotes: 1

Views: 2464

Answers (1)

Thomas Orozco
Thomas Orozco

Reputation: 55197

DJANGO_SETTINGS_MODULE

You need to configure the DJANGO_SETTINGS_MODULE environment variable in your mailalert.py script, prior to importing Django code.

Here's how you could do it:

#!/usr/bin/env python
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "benchmarks.settings")

# Do you thing now.

Virtualenv

Note that you code is probably not running inside a virtualenv right now, as made evidenced by the package paths (/usr/local/lib isn't your virtualenv):

"/usr/local/lib/python2.7/dist-packages/Django-1.5.4-py2.7.egg/django/contrib/auth/__init__.py"

Upvotes: 1

Related Questions