I am not able to connect to the database using django - python

I am able to connect to the database using MySQLdb , but not able to connect using the django
please any body help me out
All parameters are correct , like host,password and username.
when ever i tried import something python interpreter regarding django i am getting the following error
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.6/dist-packages/django/db/__init__.py", line 14, in <module>
if not settings.DATABASES:
File "/usr/local/lib/python2.6/dist-packages/django/utils/functional.py", line 276, in __getattr__
self._setup()
File "/usr/local/lib/python2.6/dist-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.
of course i have django installed.
please help me out , i am new to django....

Make sure you run python manage.py shell so that all django-specific environment variables are loaded.
If you just run python, then you'll get errors like the one you posted since the django environment is not correctly setup.

Import the value of DJANGO_SETTINGS_MODULE.
This can be either done by:
Adding the project directory to $PYTHONPATH.
Change DJANGO_SETTINGS_MODULE to projectfoldername.settings.

DJANGO_SETTINGS_MODULE - is the environment variable, set it to your projects settings.py file.
import os
os.environ['DJANGO_SETTINGS_MODULE'] = "yourprojectname.settings"
More info at : https://docs.djangoproject.com/en/dev/topics/settings/

Related

Pycharm - no django tests found but run in console

I followed this tutorial https://docs.djangoproject.com/en/3.0/intro/tutorial05/
The tests can be run by the command (polls is the application name)
python manage.py test polls
However under PyCharm IDEA, when I click on the green arrow (line 21-22).
The message is "No tests were found"
The stack trace is gibberish to me
Traceback (most recent call last): File "/Applications/PyCharm
CE.app/Contents/plugins/python-ce/helpers/pycharm/_jb_unittest_runner.py",
line 35, in
sys.exit(main(argv=args, module=None, testRunner=unittestpy.TeamcityTestRunner, buffer=not
JB_DISABLE_BUFFERING)) File
"/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/main.py",
line 100, in init
self.parseArgs(argv) File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/main.py",
line 147, in parseArgs
self.createTests() File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/main.py",
line 159, in createTests
self.module) File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/loader.py",
line 220, in loadTestsFromNames
suites = [self.loadTestsFromName(name, module) for name in names] File
"/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/loader.py",
line 220, in
suites = [self.loadTestsFromName(name, module) for name in names] File
"/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/loader.py",
line 154, in loadTestsFromName
module = import(module_name) File "/Users/raychenon/Projects/python/django/mysite/polls/test_views.py",
line 8, in
from .models import Question File "/Users/raychenon/Projects/python/django/mysite/polls/models.py", line
8, in
class Question(models.Model): File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py",
line 107, in new
app_config = apps.get_containing_app_config(module) File "/usr/local/lib/python3.7/site-packages/django/apps/registry.py", line
252, in get_containing_app_config
self.check_apps_ready() File "/usr/local/lib/python3.7/site-packages/django/apps/registry.py", line
134, in check_apps_ready
settings.INSTALLED_APPS File "/usr/local/lib/python3.7/site-packages/django/conf/init.py", line
76, in getattr
self._setup(name) File "/usr/local/lib/python3.7/site-packages/django/conf/init.py", line
61, in _setup
% (desc, ENVIRONMENT_VARIABLE)) 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.
Process finished with exit code 1
Empty suite
PyCharm IDE setup
My python interpreter is set correctly
Research
I already looked at Pycharm - no tests were found? . Unrelated error, my test functions names start by test_*
Based on your comment saying your django dependencies cannot be found, I suspect you didn't setup the python interpreter properly for your project.
Eg. if you use virtualenv, you need to setup your python interpreter to point to the python bin inside your virtualenv, so Pycharm can find your packages.
Eg. photo below shows the python interpreter for my "pmas" virtualenv.
The reason we use manage.py when working with Django is that it manages environment for us.
But working with pycharm, unless you specify things manually, a python file that has test footprints in it (importing unittest and having method names startng with "test_") are just modules we can test without any external dependencies.
in cases you use a framework such as Django, then you need to play by their rules. you will either use their tools or set whatever is needed manually.
I don't know if pycharm had this support at the time but this pycharm/django-support may help.
if that does not cover your needs, then you will need to work on a few things mentioned in Django Settings (check for other versions if you use an older one, or newer if you are from the future). your error message already mentions about this.
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.
you can either open project settings in pycharm and add this key-value in environment variables for it:
DJANGO_SETTINGS_MODULE=mysite.settings
or use this in your code wherever it is needed. (check the settings page for details)
from django.conf import settings
settings.configure(DEBUG=True)
can you try
export DJANGO_SETTINGS_MODULE=mysites.settings
here, mysites is name of Django project where settings.py is available
paste the above line in bash shell before running standalone python script

Python | Docker | Django | django.core.exceptions.ImproperlyConfigured Error

I'm trying to run a python file that is inside a container however I'm getting the following exception:
Traceback (most recent call last):
File "/tmp/e2esetup.py", line 2, in <module>
django.setup()
File "/usr/local/lib/python3.6/site-packages/django/__init__.py", line 17, in setup
configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 55, in __getattr__
self._setup(name)
File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 41, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
Code being run in docker:
docker exec -it $DOCKER_ID python /tmp/e2esetup.py
My code:
import django
django.setup()
from django.conf import settings
from django.contrib.auth.models import User
from apps.account.models import Profile
from apps.organisation.models import Organisation
....
#rest is fine for sure
I'm new to django and docker, from what I can tell I need to set the environment however I don't know how, running through manage.py does this for you or something, so if I were to run a python file through the interpreter, I have to do this manually, however I dont know how.
I also read that I need to pipe the docker environment somehow, but I'm not sure what that means either, any help is appreciated!
As the error suggests you need to set the DJANGO_SETTINGS_MODULE environment variable. It's value should be something like mysite.settings (check what it is in manage.py).
You can set it in the Dockerfile
ENV DJANGO_SETTINGS_MODULE mysite.settings
Or in the environment when you
docker exec -it -e "DJANGO_SETTINGS_MODULE=mysite.settings" $DOCKER_ID python /tmp/e2esetup.py
Or in the script itself.
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
django.setup()

django.core.exceptions.ImproperlyConfigured: Requested setting CACHES, but settings are not configured. You must either define the environment varia

I've tried everything that I could find to fix this issue, and I'm starting to tear my hair out a little.
I'm getting this error:
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.
My scripts run fine when I do:
python3 ./manage.py runserver
However, whenever I try to run tests, I get the above error...
I use a VirtualEnv, that inherits nothing globally, everything is installed (with the correct version), and within my manage.py I have set:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "<appname>.settings")
I'm using PyCharm Proffesional to develop, and I've tried running the tests in both the IDE, and in the shell.
Within the shell I'm using :
python3 manage.py test
The shell is finding no tests. The test is basic, and I'm not really all that bothered about the content of it currently as it's the environment I'm struggling with. UPDATE: I have solved the issue with the shell. Tests must be defined by:
def test_<name>():
However this hasn't solved my issue with PyCharm.
I have also called:
settings.configure()
Which told me that it was already configured.
Please note that I am not using any database with Django, and I have commented the appropriate things out of the settings.
The full error is:
Traceback (most recent call last):
File "/root/kiloenv/lib/python3.4/site-packages/django/conf/__init__.py", line 38, in _setup
settings_module = os.environ[ENVIRONMENT_VARIABLE]
File "/usr/lib/python3.4/os.py", line 631, in __getitem__
raise KeyError(key) from None
KeyError: 'DJANGO_SETTINGS_MODULE'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/<username>/Documents/<dirname>/<appname>/tests.py", line 1, in <module>
from django.test.utils import setup_test_environment
File "/root/virtualenv/lib/python3.4/site-packages/django/test/__init__.py", line 5, in <module>
from django.test.client import Client, RequestFactory
File "/root/virtualenv/lib/python3.4/site-packages/django/test/client.py", line 11, in <module>
from django.contrib.auth import authenticate, login, logout, get_user_model
File "/root/virtualenv/lib/python3.4/site-packages/django/contrib/auth/__init__.py", line 6, in <module>
from django.middleware.csrf import rotate_token
File "/root/virtualenv/lib/python3.4/site-packages/django/middleware/csrf.py", line 14, in <module>
from django.utils.cache import patch_vary_headers
File "/root/virtualenv/lib/python3.4/site-packages/django/utils/cache.py", line 26, in <module>
from django.core.cache import get_cache
File "/root/virtualenv/lib/python3.4/site-packages/django/core/cache/__init__.py", line 69, in <module>
if DEFAULT_CACHE_ALIAS not in settings.CACHES:
File "/root/virtualenv/lib/python3.4/site-packages/django/conf/__init__.py", line 54, in __getattr__
self._setup(name)
File "/root/virtualenv/lib/python3.4/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.
I have ran PyCharm under sudo to ensure that the issue wasn't permissions as I'm storing the env under root.
EDIT: I've just discovered that my tests which do not use Django are running fine, but Pycharm is still throwing several failures. These failures aren't the individual tests, they're just the error which I have mentioned here (there's 341 tests that aren't Django related). I only have one test which uses Django, which will not get past initializing and throwing the mentioned error.
Hope I've been explanitory
Use this
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
instead of
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "<appname>.settings")
In your python script, you are trying to access Django models before setting the environment try it in this order :
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "<appname>.`settings`")
from <appname>.models import Class1, Class2,...
If you are using PyCharm Pro, you can either test your app by action 'Run Django Console...'. After you click 'test', it will prompt you for the app you want to test.
or
Create a Django test in Run/Debug configuration.
since, I don't want to add this in every file, I created
a file called usercustomize.py and added this content:
import os
os.environ['DJANGO_SETTINGS_MODULE']='foosite.settings'
The file path in my case:
src/foosite/usercustomize.py
I installed foosite with "pip install -e". I am unsure if this works for normal installs.
In my case I needed to use
python3 manage.py check --deploy
instead of
django-admin check --deploy
fill "working directory" correctly with your working path
then write the copy down in it's place
I got this error when I imported TestCase from unittest2. I fixed it by importing TestCase by:
from django.test import TestCase
My suspicions were raised when the test was labelled "Unittest" rather than "Test". I had to run the whole suite before Pycharm realised I'd made this change...
If you're using PyCharm you may have forgotten to choose your debug configuration here:

from django.db import connection giving error in django1.4

I was trying to connect to the database by using the command
from django.db import connection
from the python shell
but this produced the following Import error
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/django/db/__init__.py", line 11, in <module>
if DEFAULT_DB_ALIAS not in settings.DATABASES:
File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 184, in inner
self._setup()
File "/usr/local/lib/python2.7/dist-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.
Im using Django 1.4 and PostgreSQL
the same command was executed sucessfully when i was using the earlier versions of django
Plz help.
You need to set an OS environ value for DJANGO_SETTINGS_MODULE. You can do that with a simple EXPORT command. If you are using virtualenv, I hightly recommend virtualenvwrapper and I put this setting in the 'bin/postactivate' file.
Note: I just tested it via the django 1.4 shell and the import works fine for me.
Your manage.py file defines DJANGO_SETTINGS_MODULE. Since your running this code outside of your django application, you need to define it yourself.
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", <location of settings.py>)
You have to set the environment variable DJANGO_SETTINGS_MODULE. The easiest way to do it is to put the following code at the top of the file that contains your failing import statement:
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'path/to/your/settings.py'
# ...
from django.db import connection

Unable to import models

I tried to execute
from django.db import models
but it gave the following error.. :(
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Python/2.6/site-packages/Django-1.2.2-py2.6.egg/django/db/__init__.py",
line 14, in <module>
if not settings.DATABASES:
File "/Library/Python/2.6/site-packages/Django-1.2.2-py2.6.egg/django/utils/functional.py",
line 276, in __getattr__
self._setup()
File "/Library/Python/2.6/site-packages/Django-1.2.2-py2.6.egg/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.
I'm assuming you are trying to do this import from the shell/terminal? If so you need to navigate into your Django project directory and type python manage.py shell before executing your import.
You need to add DJANGO_SETTINGS_MODULE in os.environ variables to specify which your settings file is. It seems you try to use django models outside a django app. What do you try to achieve? If you just want to test with python shell, you can use the Django shell from a Django app dir:
manage.py shell --settings=settings
UPDATE: solartic was faster ;)

Categories