python: Django import fails asking me to define DJANGO_SETTINGS_MODULE - python

I am newbee in Django.I finished the Django Tutorial once from the official djangoproject site.Not saying I know everything now, but everything worked perfectly for me till I was referring that website.
I started referring to the Practical Django projects book and somewhere in my models I tried to import :
from django.contrib.auth.models import User
gives me an import error :
ImportError Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined
`
What is really going on here ? I have been successfully importing all the packages till now then why this sudden error ?

How are you running the code that gives you the error? If you are importing the models.py in the shell, use the Django shell command
./manage.py shell
If you are trying the import in another script, you have to set the environment variable DJANGO_SETTINGS_MODULE manually.
import os
if 'DJANGO_SETTINGS_MODULE' not in os.environ:
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
This requires myproject to be in your python path.
See this similar Stack Overflow question for futher discussion.

Related

Django Trouble: django.setup() throws "ImportError: No module named 'project_name'"

I've been having an issue that I believe can be solved one of 2 ways. We have a django project I am trying to write some iPython notebooks for teaching purposes and have them in a tutorials directory that's one below the root of the project (i.e. ~/tutorials).
In the beginning of the notebooks I need to import several modules but I encountered a similar problem to the one detailed in this stack overflow question: Relative imports in Python 3 , (python couldn't find the paths, even though it could when I ran the notebooks from the root directory)
My solution was to specify the absolute path to the root of the directory in a path variable and append it like the following:
import sys
path = 'Users/greg/project_name'
sys.path.append(path)
That worked and I have been able to make the imports. However, the problem I am encountering now is that when I run a function that calls get on a Django model like so:
Platform.objects.get(name='platform_name').platform_levels.get(db_name=level).id
it raises an error from the python3.4/site-packages/django/apps/registry.py file saying:
AppRegistryNotReady: Models aren't loaded yet.
Does anybody have any insight into why they aren't being loaded and what I need to do differently? Please let me know if there's other information that I should provide to help you answer this question. Thanks!
Edit: The suggestion by #albar led to a new error which I think is the root of all the issues. When I go to run django.setup(), it raises an error on this line:
mod = importlib.import_module(self.SETTINGS_MODULE)
saying:
ImportError: No module named 'project_name'
Does it need to be able to import the entire project as a module and if so, how do I tell it how to find it?
You have to setup Django in your script:
import django
django.setup()
EDIT: Before that, you have to define your settings module:
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings'

Django Python Shell

How do I enter the Django Shell? I am not seeing clear instructions on how to achieve this.
You can run that code interactively in the dev shell.
python manage.py shell
For future reference, though: all you need to do to make a plain .py file "Django compatible" is that you set the DJANGO_SETTINGS_MODULE environment variable before importing any Django stuff:
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproj.settings")
from myapp.models import Stuff
# ...

Using template in Django tutorial

I'm on Chapter 4: Templates of the Django tutorial, and I'm trying to run the following in an Emacs inferior mode using Python:
>>> from django import template
>>> t = template.Template('My name is {{ name }}.')
>>> c = template.Context({'name': 'Adrian'})
>>> print t.render(c)
My name is Adrian.
>>> c = template.Context({'name': 'Fred'})
>>> print t.render(c)
My name is Fred.
But I get the error here.
A quick search suggests that I should do be setting my DJANGO_SETTINGS_MODULE like so:
>>> import os
>>> os.environ["DJANGO_SETTINGS_MODULE"] = "settings.py"
However, I run into this error:
ImportError: Could not import settings 'settings.py' (Is it on sys.path?): No module named settings.py
I'm using Fedora 16. How do I correctly resolve this problem?
You can do this in the python manage.py shell, since that would have settings.py in . directory.
Otherwise:
Consider settings.py just another python library and you need to ensure its added to sys.path and then you can do as follows :
import settings
from django.core.management import setup_environ
setup_environ(settings) # Setting up the env settings
This sets up the settings to your environment. [ This is the right way ]
There is no secret recipe in settings.py and since django in itself is a library to python, so it could not be default set any paths to your sys.path unless imported and executed - as I suggested.
You should really use setup_environ as suggested in another answer.
A hint regarding this specific exception: DJANGO_SETTINGS_MODULE is a Python module name, so it may not end with ".py". Usually, this would be your_django_site.settings and the module/directory your_django_site has to be in sys.path.
All Django code not in a project should either be run from the Django REPL, available via ./manage.py shell, or run as a standalone script.
In order to test anything in the shell for Django, you should use the Django shell:
python manage.py shell
This will start up a Python interpreter which will magically have your settings file (and the rest of your project) on the Python path.
(This assumes you have a project already. If not, use django-admin.py startproject my_project_name.)

Django settings.py Error: Import by filename is not supported

I am running Django in a virtual environment (using virtualenv), and I'm trying to add a custom development environment settings file to simplify app configuration when I'm developing. My plan was to do this with two lines of code
if os.environ.get('DEVELOPMENT', None):
from login import settings_dev
I've also tried import settings_def and from login.settings_dev import *. My settings_dev.py file is sitting in the same directory as my settings.py file and my app is sitting in a folder called login. When I run python login/manage.py syncdb I get this error:
Error: Import by filename is not supported.
My searching keeps bringing up DJANGO_SETTINGS_MODULE (though I'm not sure how it plays into all this - first Django app :]), so just an FYI it is set in my settings.py file like so:
os.environ['DJANGO_SETTINGS_MODULE'] = 'login.settings'
I've also tried exporting it in my terminal, but I get the same error.
Does anyone know how I can fix this/what I'm doing wrong here?
Make sure while passing relative address of file to use "." instead of "/".
I faced the same error what I actually did
"music/urls"
But it should be
"music.urls"
In the original settings.py, at the very end:
try:
from settings_dev import *
except ImportError:
pass
Create settings_dev.py in the same directory as settings.py, and in it, add these two lines at the very top:
import sys
globals().update(vars(sys.modules['settings']))
Now add whatever development settings you want in this file.
I had similar error in runserver command execution and finally I've found that this error raises because of python version incompatibility by the django version installed. There is two versions of python on my system and I had running django server by the wrong one. Hope it could be helpful to someone.

Sys.path modification or more complex issue?

I have problems with importing correctly a module on appengine. My app generally uses django with app-engine-patch, but this part is task queues using only the webapp framework.
I need to import django settings for the app to work properly.
My script starts with:
import os
import sys
sys.path.append('common/')
# Force Django to reload its settings.
from django.conf import settings
settings._target = None
# Must set this env var before importing any part of Django
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
I always get this error, or something related:
<type 'exceptions.ImportError'>: No module named ragendja.settings_pre
because the settings.py file starts with
from ragendja.settings_pre import *
I think I need to add ragendja to sys.path again but I had several tries that didn't work.
Here is my directory:
project/
app.yaml
setting.py
common/
appenginepatch/
ragendja/
setting_pre.py
myapp/
script.py
Is it only a sys.path problem and how do I need to modify it with the correct syntax?
Thanks
App engine patch manipulates sys.path internally. Background tasks bypass that code, so your path will not be ready for Django calls. You have two choices:
Fix the paths manually. The app engine documentation (see the sub-section called "Handling import path manipulation") suggests factoring the path manipulation code into a module that can be imported by your task script.
Eliminate dependencies on django code, if possible. If you can write your task to be pure python and/or google api calls, you're good to go. In your case, this might mean refactoring your settings code.
Why not:
sys.path.append('common/appenginepatch')
since the ragendja is in this directory?

Categories