Problem importing from User models

2

I'm doing some testing on a Django project, I've created a very simple module just for testing myself. Follow below:

from django.contrib.auth.models import User

def teste():
    for i in User.objects.all():
        print i.username

if __name__ == "__main__":
    teste()

When executing the code, this error is returned:

Traceback (most recent call last):
File "teste.py", line 6, in <module>
from django.contrib.auth.models import User
File "/home/carlos/myworkspace/helpdesk/lib/python2.7/site-packages/django   /contrib/auth/__init__.py", line 6, in <module>
from django.middleware.csrf import rotate_token
File "/home/carlos/myworkspace/helpdesk/lib/python2.7/site-packages/django  /middleware/csrf.py", line 14, in <module>
from django.utils.cache import patch_vary_headers
File "/home/carlos/myworkspace/helpdesk/lib/python2.7/site-packages/django/utils/cache.py", line 26, in <module>
from django.core.cache import get_cache
File "/home/carlos/myworkspace/helpdesk/lib/python2.7/site-packages/django/core/cache/__init__.py", line 69, in <module>
if DEFAULT_CACHE_ALIAS not in settings.CACHES:
File "/home/carlos/myworkspace/helpdesk/lib/python2.7/site-packages/django/conf/__init__.py", line 54, in __getattr__
self._setup(name)
File "/home/carlos/myworkspace/helpdesk/lib/python2.7/site-packages/django/conf/__init__.py", line 47, 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.

NOTE: Within the python manage.py shell with the command% run test.py, the code works.

    
asked by anonymous 12.05.2014 / 17:04

1 answer

2

This is not the "common" way to run a project with Django, but if you just want to solve the problem in question, the solution is to set the DJANGO_SETTINGS_MODULE variable.

When you run the command by python manage.py shell , this variable is set automatically, which in this case does not cause the error.

To set the variable manually, you can put the following code at the beginning of your script:

import os
# estou considerando que o nome do projeto (e não o app!) seja "helpdesk"
os.environ['DJANGO_SETTINGS_MODULE'] = 'helpdesk.settings' 

Another option is to set the variable in your shell instead of the code. So:

export DJANGO_SETTINGS_MODULE=helpdesk.settings

In any case, I recommend that you do not do it that way. It is simpler and more reliable to use manage.py , or to make a "traditional" code using templates, views and templates.

    
12.05.2014 / 17:29