Why am I getting this error in Django? - python

I have a script that imports a models.py from an app, but it will not import!
I don't believe I am supposed to manually create an "export DJANGO..." environment variable...I'm doing something else wrong.
Traceback (most recent call last):
File "parse.py", line 8, in ?
from butterfly.flower.models import Channel, Item
File "/home/user/shri/butterfly/flower/models.py", line 1, in ?
from django.db import models
File "/usr/lib/python2.4/site-packages/django/db/__init__.py", line 10, in ?
if not settings.DATABASE_ENGINE:
File "/usr/lib/python2.4/site-packages/django/utils/functional.py", line 269, in __getattr__
self._setup()
File "/usr/lib/python2.4/site-packages/django/conf/__init__.py", line 38, in _setup
raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE)
ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.

You need to properly import your settings file. If you don't import the django environment variables first, your import will fail as you've noticed. You need to code something like:
import os
# Set the DJANGO_SETTINGS_MODULE environment variable.
os.environ['DJANGO_SETTINGS_MODULE'] = "myproject.settings"
#do your stuff

I don't believe I am supposed to
manually create an "export DJANGO..."
environment variable...
Manually or otherwise, you are supposed to ensure that variable is in the environment before you import a Django models file -- not sure what the causes are for your disbelief, but, whatever they may be, that disbelief is ill-founded.

from command line ran "python manage.py shell" should include the right settings for you and give you the python prompt.

One alternative to messing about with the environment is to just write your script as a Django custom management command, which takes care of setting up the environment for you (along with other things like option parsing, etc).

I had this similar error, and I realized that I forgot to create the file "init.py" in to the app folder:
myapp:
manage.py
myapp:
__init__.py
settings.py
....

From command line, please execute this command. This may help you:
export DJANGO_SETTINGS_MODULE=projectname.settings

Related

django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured

I want to connect MySQL database to my django project, but it is throwing an error :
"django.core.exceptions.ImproperlyConfigured: Requested setting
USE_I18N, but settings are not configured. You must either define the
environment variable DJANGO_SETTINGS_MODULE or call
settings.configure() before accessing settings."
Trace:
(myenv) LIBINGLADWINs-MacBook-Air:libinrenold$ django-admin dbshell
Traceback (most recent call last):
File "/Users/libinrenold/Desktop/djangoworks/myenv/bin/django-admin", line 11, in <module>
sys.exit(execute_from_command_line())
File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
utility.execute()
File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/core/management/base.py", line 322, in execute
saved_locale = translation.get_language()
File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/utils/translation/__init__.py", line 195, in get_language
return _trans.get_language()
File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/utils/translation/__init__.py", line 59, in __getattr__
if settings.USE_I18N:
File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__
self._setup(name)
File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/conf/__init__.py", line 39, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
settings.py.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'test',
'USER': 'user',
'PASSWORD': 'root',
'HOST':'',
'PORT': '',
}
}
You must define the relevant variable to show where your settings.py file lives:
export DJANGO_SETTINGS_MODULE=mysite.settings
This is the relevant docs entry:
When you use Django, you have to tell it which settings you’re using.
Do this by using an environment variable, DJANGO_SETTINGS_MODULE.
The value of DJANGO_SETTINGS_MODULE should be in Python path syntax,
e.g. mysite.settings. Note that the settings module should be on the
Python import search path.
If you are using a virtualenv (which is the best practice), you can paste the relevant export command in the file <path-to-virtualenv>/bin/activate
It happens to me too, I just now found unintentional.
I changed "configuration" in top of PyCharm IDE so pycharm confused when try to run django code. Exactly the problem popup when I try to run server with shortcut but when I used terminal to run server, I found django code not having any problem and pycharm can't found setting.
So please check "configuration" in top pycharm's ide maybe you do same mistake :)
I'm new in django so be calm if my answer was silly.
I had this problem because I tried to import a django script after just typing
python
instead of
python manage.py shell
Duh!
Problem
I had the same error with Django==3.2 and djangorestframework==3.12.4 (2021/04) when I ran unittest. In my case, the python manage.py test works properly but I cannot directly run or debug the test module which was in a specific app, and I get this error:
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
Solution
First I added the django project root to the sys.path. Then I added DJANGO_SETTINGS_MODULE to the environment variable to address the project setting root and called the Django setup function. This is my code:
from os import path, environ
from sys import path as sys_path
from django import setup
sys_path.append(<path to django setting.py>)
environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_project.settings')
setup()
put this in top of settings.py
this will configure django for you
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", __file__)
import django
django.setup()
I had the same error with Django 3.0.8 (july 2020) when trying to run the server, and in my case no need for the DJANGO_SETTINGS_MODULE environment variable. The solution is to use another form to run the server:
cd <directory containing manage.py>
python3 manage.py runserver
It works to run Django shell too :
python3 manage.py shell
Like raratiru answered, you need DJANGO_SETTINGS_MODULE environment variable defined with the relative pythonic path to your setting file.
OR use your django-admin command with the settings parameter:
django-admin --settings=mysite.settings dbshell
Below code in terminal to manually inform which settings I am using worked for me:
set DJANGO_SETTINGS_MODULE=mysite.settings
Dear all I faced the same problem and i scrapped the web to find a solution. None of the one above solved anything.
The issue in my case was related to a wrong configuration of pycharm. As for someone above the app didnt have any issue when launched from the command line/ shell.
The issue is here:
For some reason the env variable disappeared. i added back and everything started to work again without any issue.

ModuleNotFoundError error with PyCharm project folder recs

I am working on a project in PyCharm. The project has the following structure:
/projectRoot/
folder1/
somecode.py
utils/
__init__.py
myutils1.py
I'd want to know how I can do an import such that the import works when running the code in the pyCharm console in an interactive manner, as well as when running the code using the
python somecode.py
command in the terminal.
Currently I do:
from utils.myutils1.py import myClass
But command line I get the error:
File "somecode.py", line 10, in
from utils.myutils1 import myClass ModuleNotFoundError: No module named 'utils'
and on PyCharm:
Traceback (most recent call last): File
"/home/ubuntu/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py",
line 2881, in run_code
exec(code_obj, self.user_global_ns, self.user_ns) File "", line 1, in
from utils.myutils1 import myClass ModuleNotFoundError: No module named 'utils'
Any recommendations on the proper folder structure for modules within a project, and how to import them properly?
Thanks!
To explain the answer I recreated that project structure you had
/projectRoot/
folder1/
somecode.py
utils/
__init__.py
myutils1.py
somecode.py
from utils.myutils1 import myclass
if __name__ == "__main__":
print(myclass)
myutils1.py
myclass="tarun"
Running them from pycharm works without any issues, but running them from terminal will produce below error
File "somecode.py", line XX, in <module>
from utils.myutils1 import myclass
ModuleNotFoundError: No module named 'utils'
The issue is that Pycharm does few things for you because which you don't realize why it is not working in the terminal. So before telling you what you need to, I will tell you two things that PyCharm does on its own.
Python Console
When you launch a Python Console from Pycharm, there is some code that gets executed, using preferences.
As you can see there are two options
[X] Add content roots to PYTHONPATH
[ ] Add source roots to PYTHONPATH
And then a starting script as well. So what this does is that it adds the root of your project to python's path. Which is controlled by two main ways sys.path and PYTHONPATH environment variable
If I run the below code in Python Console
>>> import sys
>>> sys.path
['/Applications/PyCharm.app/Contents/helpers/pydev',
'/Applications/PyCharm.app/Contents/helpers/pydev',
'/Users/tarun.lalwani/.virtualenvs/folderstructure27/lib/python27.zip',
'/Users/tarun.lalwani/.virtualenvs/folderstructure27/lib/python2.7', ....
'/Users/tarun.lalwani/.virtualenvs/folderstructure27/lib/python2.7/site-packages',
'/Users/tarun.lalwani/Desktop/payu/projects/folderstructure27']
As you can see '/Users/tarun.lalwani/Desktop/payu/projects/folderstructure27' is added to the Python terminal.
Python Configurations
When you configure to RUN in code using Pycharm, you have similar two options.
We can change the code of our somecode.py to below
import os
print (os.environ['PYTHONPATH'])
import sys
print (sys.path)
/Users/tarun.lalwani/Desktop/payu/projects/folderstructure27
['/Users/tarun.lalwani/Desktop/payu/projects/folderstructure27/folder1',
'/Users/tarun.lalwani/Desktop/payu/projects/folderstructure27', ....,
'/Users/tarun.lalwani/.virtualenvs/folderstructure27/lib/python2.7/site-packages']
From the output we can see that PYTHONPATH is set to current project folder.
Running from terminal
Now let's run the somecode.py from terminal with the modifications we made.
$ python somecode.py
Traceback (most recent call last):
File "somecode.py", line 2, in <module>
print (os.environ['PYTHONPATH'])
File "/Users/tarun.lalwani/.virtualenvs/folderstructure27/bin/../lib/python2.7/UserDict.py", line 40, in __getitem__
raise KeyError(key)
KeyError: 'PYTHONPATH'
So that indicates there is no PYTHONPATH when we ran it in terminal. Let us run it again by removing the print(os.environ['PYTHONPATH']) code. You will get the below output
['/Users/tarun.lalwani/Desktop/payu/projects/folderstructure27/folder1', ...
'/Users/tarun.lalwani/.virtualenvs/folderstructure27/lib/python2.7/site-packages']
Traceback (most recent call last):
File "somecode.py", line 7, in <module>
from utils.myutils1 import myclass
ImportError: No module named utils.myutils1
As you can see folder1 is added to sys.path because it is the folder containing somecode.py, but the root folder has not been added. The fix in terminal is simple, which is to set the root directory path in PYTHONPATH.
PYTHONPATH=`pwd`/.. python somcode.py
And now the code will work from terminal also.
But the way they work are different from Python Console.
IMPORTANT NOTE:
Python Console using PyCharm on remote interpreter.
If running the python console using the remote interpreter option pycharm will fail. This is because it will append the path of the local PC and not the path of the remote server.
In order to fix this problem one has to add a mapping between the local PC directory and the remote server path.
You can use utils package inside folder1 folder:
Then the code will work either way:
from utils.myutils1 import myClass
Similar error here and this appears to be working for me:
Make sure Project Interpreter is set to, for example: C:\Python36\python.exe (in my case) and not a copy somewhere or another.
'File > Settings > Project ____ > Project Interpreter'
Or, long story short, if that route isn't cooperating, can also try finding workspace.xml and manually change SDK_HOME before starting PyCharm:
<option name="SDK_HOME" value="C:\Python36\python.exe" />

django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured

I'm trying to run a populate script which I put together from the tango_with_django tutorial (https://github.com/leifos/tango_with_django/blob/master/tango_with_django_project/populate_rango.py) however I'm getting the below traceback and it seems to be related to changes made in Django 1.7? I'd appreciate if someone could explain what I'm doing wrong here.
(test_env) C:\Users\WriteCode\test_env\epl>python populate_clubs.py
Traceback (most recent call last):
File "populate_clubs.py", line 4, in <module>
django.setup()
File "c:\Python27\lib\site-packages\django\__init__.py", line 20, in setup
configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
File "c:\Python27\lib\site-packages\django\conf\__init__.py", line 46, in __ge
tattr__
self._setup(name)
File "c:\Python27\lib\site-packages\django\conf\__init__.py", line 40, in _set
up
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, b
ut settings are not configured. You must either define the environment variable
DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
(test_env) C:\Users\WriteCode\test_env\epl>
My populate_clubs.py script
import os
import sys
import django
django.setup()
def add_club(name, nickname, manager, established, stadium, active=True):
c = clubs.objects.get_or_create(name=name, nickname=nickname, manager=manager, established=established, stadium=stadium, active=active)
return c
def populate():
add_club(name = "Aston Villa",
nickname = "Villans",
manager = "Tim Sherwood",
established = "1897",
stadium = "Villa Park"
)
# Print out what was added
for c in clubs.objects.all():
print "The following has been added to clubs:" + c
# Start execution
if __name__ == '__main__':
print "Starting club population script..."
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'epl.settings')
from teams.models import clubs
populate()
You can insert os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") before the django.setup() line.
Call to django.setup() should go after setting DJANGO_SETTINGS_MODULE environment variable. Just move it into your __main__ right after os.environ.setdefault().
If you are getting a similar error after initiating your interaction with Django by running python in a terminal, running python manage.py shell in the appropriate directory may solve your issue.
For development and debugging, you may use the standalone python package.
Install with pip
pip install standalone
Use standalone to use Django from the module.
# add the following to the top of the module.
import standalone
standalone.run('mysite.settings') # replace with your settings module.
# your code goes below the configuration
import os
import sys
# ... .. . whole module
Now you may run the module as a Python Django script.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'epl.settings')
should be above
import django
which is you should call django_settings_module before importing and calling django setup.
Hope this is helpful.
If you're running PyCharm, what worked for me was to invalidate the cache and restart the app.
File => Invalidate Caches / Restart ...
My virtualenv had been recently updated from Python 3.6 or 3.7 to 3.8.
It happened to me when I used django related import statement in a non-django module.
i.e from index.views import view that did raise an error for me.
I met the same problem when setting the environment.
(I tried to add the:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_project.settings")
into the "Starting script window",which is in the Django Console or rewrite the .wsgi file, But all of them were failed)
My final solution: (open the terminal and set the environment manually)
Here are the steps:(for mac)
open the terminal and type vim ~/.bash_profile
add below lines:
PATH=${PATH}:/Users/work/workspace/[virtual_environment]/bin
PYTHONPATH=${PATH}:/Users/work/PycharmProjects/[project_name]
DJANGO_SETTINGS_MODULE=[project_name].settings
type :wq to save and exit terminal
type source ~/.bash_profile to reload it
it will work when you run python manage.py shell this time.
Make sure to activate your venv first by scripts/activate venv then in your populate_user.py right after import os run os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'epl.settings') this should work.

Django documentation: Models; error from line 1 of code

In the Django documentation on Models, the first command that I am asked to run and python's response was:
>>> from django.db import models
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
from django.db import models
File "C:\Python26\lib\site-packages\django\db\__init__.py", line 11, in <module>
if DEFAULT_DB_ALIAS not in settings.DATABASES:
File "C:\Python26\lib\site-packages\django\utils\functional.py", line 184, in inner
self._setup()
File "C:\Python26\lib\site-packages\django\conf\__init__.py", line 40, in _setup
raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE)
ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
As you can see from the stack trace, I am running a django server in python 2.6.6. Could anyone offer me a clue to start off on the right foot with this tutorial? Thanks in advance.
Are you running these commands from ./manage.py shell? You cannot run django commands from the regular python shell without specifying where your settings.py file is for the project. Django's ./manage.py shell command specifies that for you, making it easier to do django stuff on the command line.
If you don't see a file named manage.py in your current working directory, then that probably means you're not in the directory of your django application, or you haven't started one yet.
Edit: Also, that documentation is meant as an example of what to put in your application's models.py file, not something you should type in on the command line. That doesn't mean it won't work on the command line (if you use manage.py shell) but it isn't what the documentation is suggesting. Check the tutorial if you're unclear on how to start the shell and what files go where.
You're doing it wrong.
$ python manage.py shell
The answer here definitely works for the interactive prompt, which I was using, however I don't think that the intention of the first block of code was intended to actually be run! Immediately following that first code in the models documentation, you are expected to put the next codes into your models.py file created during the previous tutorial... I guess that's why they subtly labeled that section "Quick Example." What a headache!
Futhermore, that paragraph goes on to say "The above Person model would create a database table like..." suggesting that it was never intended to actually be run as-is.

Running Django custom manage.py task on Heroku - Importing Issues

I'm trying to run a custom django command as a scheduled task on Heroku. I am able to execute the custom command locally via: python manage.py send_daily_email. (note: I do NOT have any problems with the custom management command itself)
However, Heroku is giving me the following exception when trying to "Run" the task through Heroku Scheduler addon:
Traceback (most recent call last):
File "bin/send_daily_visit_email.py", line 2, in <module>
from django.conf import settings
ImportError: No module named django.conf
I placed a python script in /bin/send_daily_email.py, and it is the following:
#! /usr/bin/python
from django.conf import settings
settings.configure()
from django.core import management
management.call_command('send_daily_email') #delegates off to custom command
Within Heroku, however, I am able to run heroku run bin/python - launch the python shell - and successfully import settings from django.conf
I am pretty sure it has something to do with my PYTHON_PATH or visibility to Django's SETTINGS_MODULE, but I'm unsure how to resolve the issue. Could someone point me in the right direction? Is there an easier way to accomplish what I'm trying to do here?
Thank you so much for your tips and advice in advance! New to Heroku! :)
EDIT:
Per Nix's comment, I made some adjustments, and did discover that specifying my exact python path, I did get past the Django setup.
I now receive:
File "/app/lib/python2.7/site-packages/django/core/management/__init__.py", line 155, in call_command
raise CommandError("Unknown command: %r" % name)
django.core.management.base.CommandError: Unknown command: 'send_daily_email'
Although, I can see 'send_daily_email' when I run ``heroku run bin/python app/manage.py```.
I'll keep an update if I come across the answer.
You are probably using a different interpreter.
Check to make sure shell python is the same as the one you reference in your script /usr/bin/python . It could be that there is a different one in your path, which would explain why it works when you run python manage.py but not your shell scrip which you explicitly reference /usr/bin/python.
Typing which python will tell you what interpreter is being found on your path.
In addition, this can also be resolved by adding your home directory to your Python path. A quick and unobtrusive way to accomplish that is to add it to the PYTHONPATH environment variable (which is generally /app on the Heroku Cedar stack).
Add it via the heroku config command:
$ heroku config:add PYTHONPATH=/app
That should do it! For more details: http://tomatohater.com/2012/01/17/custom-django-management-commands-on-heroku/

Categories

Resources