Django databases: problems with the test database - python

I am learning about Django testing.
I wrote a simple App with a simple model and would like to run tests to check the validity of a model method, but I get an error message when I run the test:
here's models.py
from django.db import models
class Trip(models.Model):
origin = models.CharField(max_length=20)
destination = models.CharField(max_length=20)
def __str__(self):
return self.origin
def is_valid(self):
return self.origin != self.destination
Here's test.py
from django.test import TestCase
from .models import Trip
# Create your tests here.
class TripModelTests(TestCase):
def test_trip(self):
a = Trip.objects.create(origin='a', destination='a')
self.assertIs(a.is_valid(), True)
here is settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'd57r9kcrhthdc7',
'USER': 'sdqxaruartlvrd',
'PASSWORD': 'e7b8f85611596ed125fe3ed4ea590f821f65e317c17ee7871be75b8130d72378',
'HOST': 'ec2-3-214-46-194.compute-1.amazonaws.com',
'PORT': '5432',
'TEST': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
}
and here is the error message i get when I run python manage.py test transport
Creating test database for alias 'default'...
Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\fabia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
utility.execute()
File "C:\Users\fabia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\fabia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\test.py", line 23, in run_from_argv
super().run_from_argv(argv)
File "C:\Users\fabia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\fabia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 371, in execute
output = self.handle(*args, **options)
File "C:\Users\fabia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\test.py", line 53, in handle
failures = test_runner.run_tests(test_labels)
File "C:\Users\fabia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\test\runner.py", line 695, in run_tests
old_config = self.setup_databases(aliases=databases)
File "C:\Users\fabia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\test\runner.py", line 614, in setup_databases
return _setup_databases(
File "C:\Users\fabia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\test\utils.py", line 170, in setup_databases
connection.creation.create_test_db(
File "C:\Users\fabia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\base\creation.py", line 55, in create_test_db
self._create_test_db(verbosity, autoclobber, keepdb)
File "C:\Users\fabia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\base\creation.py", line 172, in _create_test_db
'dbname': self.connection.ops.quote_name(test_database_name),
File "C:\Users\fabia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\postgresql\operations.py", line 113, in quote_name
if name.startswith('"') and name.endswith('"'):
AttributeError: 'WindowsPath' object has no attribute 'startswith'
The test works fine if I just use the default django settings and use a sqlite database....

The error could be due to your BASE_DIR path, in your settings.py, you need to remove the slash / and switch it over to the following
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
You may need to verify depending on your BASE_DIR contents that it points to the right place. One way to debugging this is to set ipdb() just after your database dictonary, so once you use python manage.py runserver, can can easily inspect the DATABASES structure.
import ipdb; ipdb.set_trace()
Source: https://pypi.org/project/ipdb/

Related

Django Error : 'No module named django.sessions' [duplicate]

This question already has an answer here:
ImportError: No module named django.sessions
(1 answer)
Closed 5 years ago.
I'm getting an error in my Django Project and I would like to find a solution.
I developped my project with MySQL Database, but after some discussions, I would like to replace MySQL by NoSQL Database (and Django ORM commands by Django MongoDB commands) like MongoDB for different reasons :
Ability to handle billions lines
Ability to make Big Data (Hadoop, ...)
My Django project settings looks like :
import mongoengine
from mongoengine import connect
AUTHENTICATION_BACKENDS = (
'mongoengine.django.auth.MongoEngineBackend',
)
SESSION_ENGINE = 'mongoengine.django.sessions'
SESSION_SERIALIZER = 'mongoengine.django.sessions.BSONSerializer'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.dummy'
}
}
MONGO_DATABASE_NAME = 'XXX'
MONGO_HOST = '172.30.10.X'
MONGO_PORT = 27017
connect(MONGO_DATABASE_NAME, host=MONGO_HOST, port=MONGO_PORT)
And, when I run : python manage.py runserver
I get :
System check identified 1 issue (0 silenced).
March 20, 2017 - 10:33:20
Django version 1.10.3, using settings 'Etat_civil.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Unhandled exception in thread started by <function wrapper at 0x104994140>
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 142, in inner_run
handler = self.get_handler(*args, **options)
File "/usr/local/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/runserver.py", line 27, in get_handler
handler = super(Command, self).get_handler(*args, **options)
File "/usr/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 64, in get_handler
return get_internal_wsgi_application()
File "/usr/local/lib/python2.7/site-packages/django/core/servers/basehttp.py", line 59, in get_internal_wsgi_application
sys.exc_info()[2])
File "/usr/local/lib/python2.7/site-packages/django/core/servers/basehttp.py", line 49, in get_internal_wsgi_application
return import_string(app_path)
File "/usr/local/lib/python2.7/site-packages/django/utils/module_loading.py", line 20, in import_string
module = import_module(module_path)
File "/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/valentinjungbluth/Desktop/Django/Etat_civil/Etat_civil/wsgi.py", line 16, in <module>
application = get_wsgi_application()
File "/usr/local/lib/python2.7/site-packages/django/core/wsgi.py", line 14, in get_wsgi_application
return WSGIHandler()
File "/usr/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 153, in __init__
self.load_middleware()
File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 58, in load_middleware
mw_instance = mw_class()
File "/usr/local/lib/python2.7/site-packages/django/contrib/sessions/middleware.py", line 15, in __init__
engine = import_module(settings.SESSION_ENGINE)
File "/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
django.core.exceptions.ImproperlyConfigured: WSGI application 'Etat_civil.wsgi.application' could not be loaded; Error importing module: 'No module named django.sessions'
I know that lastest mongoengine updates doesn't support sessions, so I downloaded mongoengine==0.9.0 but it seems to not work.
Do you have an idea ?
I haven't experienced using mongodb as an engine but the Django documentation says the database should be declared using this format:
Read https://docs.djangoproject.com/en/1.10/ref/databases/
DATABASES = {
'default': {
'ENGINE': django_mongodb_engine',
'NAME': 'XXX',
'USER': 'a_user',
'PASSWORD': 'a_password',
'HOST': '',
'PORT': '',
}
}

Using MongoDB as backend for Django: Error running "python manage.py migrate"

I am new to Django and wanted to use django with Mongodb as backend. I started with the examples given in the internet. but facing issues when i tried to run migrate.
Installed: django 1.8, pymongo 2.8, mongodb
Models.py
from __future__ import unicode_literal
from mongoengine import *
class Choice(EmbeddedDocument):
choice_text = StringField(max_length=200)
votes = IntField(default=0)
class Poll(Document):
question = StringField(max_length=200)
pub_date = DateTimeField(help_text='date published')
choices = ListField(EmbeddedDocumentField(Choice))
Setttings.py : Created a user "mango" in mongodb. mongodb was running fine
import mongoengine
from mongoengine import connect
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.dummy',
},
}
SESSION_ENGINE = 'mongoengine.django.sessions'
_MONGODB_USER = 'mango'
_MONGODB_PASSWD = 'mango'
_MONGODB_HOST = 'localhost'
_MONGODB_NAME = 'performance'
_MONGODB_DATABASE_HOST = \
'mongodb://%s:%s#%s/%s' \
% (_MONGODB_USER, _MONGODB_PASSWD, _MONGODB_HOST, _MONGODB_NAME)
mongoengine.connect(_MONGODB_NAME, host=_MONGODB_DATABASE_HOST)
AUTHENTICATION_BACKENDS = (
'mongoengine.django.auth.MongoEngineBackend',
)
I tried to run python manage.py migrate, it was throwing the below error. But i am able to connect to Db from shell. Can someone of you please help me in understanding the problem?
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 353, in execute_from_command_line
utility.execute()
File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 302, in execute
settings.INSTALLED_APPS
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 55, in __getattr__
self._setup(name)
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 43, in _setup
self._wrapped = Settings(settings_module)
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 99, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module
__import__(name)
File "C:\Users\pm348b\Desktop\Praneeth_Desktop\Python_Programs\TEST\mysite\mysite\settings.py", line 118, in <module>
mongoengine.connect(_MONGODB_NAME, host=_MONGODB_DATABASE_HOST)
File "C:\Python27\lib\site-packages\mongoengine\connection.py", line 165, in connect
return get_connection(alias)
File "C:\Python27\lib\site-packages\mongoengine\connection.py", line 128, in get_connection
raise ConnectionError("Cannot connect to database %s :\n%s" % (alias, e))
mongoengine.connection.ConnectionError: Cannot connect to database default :
command SON([('saslStart', 1), ('mechanism', 'SCRAM-SHA-1'), ('autoAuthorize', 1), ('payload', Binary('n,,n=mango,r=OTc3NDkxNTE3NTM3', 0))]) on namespace performance.$cmd failed: Authentication failed.
DATABASES = {
'default': {
'ENGINE': 'djongo',
'NAME': 'Name of the Cluster',
'HOST': 'The link which mongo provides for python',
'USER': "Created User's username",
'PASSWORD': 'Password of the above user',
}
Use this in your settings.py file

Django cannot run tests when DATABASES 'default' is empty

I have some troubles running tests with setting DATABASES['default'] = {}.
I got the folowing error when running ./manage.py test
$ ./manage.py test --failfast
Creating test database for alias 'mydb'...
E
======================================================================
ERROR: test_admin (myapp.test.MyTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/thomas/.virtualenvs/tmpapp/local/lib/python2.7/site-packages/django/test/testcases.py", line 182, in __call__
self._pre_setup()
File "/home/thomas/.virtualenvs/tmpapp/local/lib/python2.7/site-packages/django/test/testcases.py", line 754, in _pre_setup
self._fixture_setup()
File "/home/thomas/.virtualenvs/tmpapp/local/lib/python2.7/site-packages/django/test/testcases.py", line 887, in _fixture_setup
if not connections_support_transactions():
File "/home/thomas/.virtualenvs/tmpapp/local/lib/python2.7/site-packages/django/test/testcases.py", line 874, in connections_support_transactions
for conn in connections.all())
File "/home/thomas/.virtualenvs/tmpapp/local/lib/python2.7/site-packages/django/test/testcases.py", line 874, in <genexpr>
for conn in connections.all())
File "/home/thomas/.virtualenvs/tmpapp/local/lib/python2.7/site-packages/django/utils/functional.py", line 55, in __get__
res = instance.__dict__[self.func.__name__] = self.func(instance)
File "/home/thomas/.virtualenvs/tmpapp/local/lib/python2.7/site-packages/django/db/backends/__init__.py", line 782, in supports_transactions
self.connection.leave_transaction_management()
File "/home/thomas/.virtualenvs/tmpapp/local/lib/python2.7/site-packages/django/db/backends/__init__.py", line 338, in leave_transaction_management
if managed == self.get_autocommit():
File "/home/thomas/.virtualenvs/tmpapp/local/lib/python2.7/site-packages/django/db/backends/__init__.py", line 345, in get_autocommit
self.ensure_connection()
File "/home/thomas/.virtualenvs/tmpapp/local/lib/python2.7/site-packages/django/db/backends/__init__.py", line 133, in ensure_connection
self.connect()
File "/home/thomas/.virtualenvs/tmpapp/local/lib/python2.7/site-packages/django/db/utils.py", line 86, in __exit__
db_exc_type = getattr(self.wrapper.Database, dj_exc_type.__name__)
AttributeError: 'DatabaseWrapper' object has no attribute 'Database'
----------------------------------------------------------------------
Ran 0 tests in 0.001s
FAILED (errors=1)
Destroying test database for alias 'mydb'...
settings.py
..
DATABASES = {
'default': {},
'mydb': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
},
}
DATABASE_ROUTERS = ['myapp.router.MyRouter']
router.py
class MyRouter:
def db_for_read(self, model, **hints):
return 'mydb'
def db_for_write(self, model, **hints):
return 'mydb'
def allow_migrate(self, db, model):
if db == 'default':
return False
return True
test.py
from django.test import TestCase
class MyTest(TestCase):
def test_admin(self):
self.assertEqual(1, 1)
I did some investigation and find that self.connect() was called on the dummy backend associated with 'default' alias. Since the dummy backend does not implement much fonctionnalities, the call fails. How can I run tests with DATABASES['default'] = {} ?
Use different settings.py files for production/development/testing (best).
And or use Sqlite as default entry (quickest).

AttributeError: 'Settings' object has no attribute 'DATABASE_ENGINE'

Im new to django and python, trying to run a piece of django code on my system but im running into these problems , im running version 2.7 python and v1.4 django
$ python manage.py runserver
Running in development mode.
Running in development mode.
Running in development mode.
Running in development mode.
Validating models...
HACKUING USER MODEL
Unhandled exception in thread started by <bound method Command.inner_run of <django.contrib.staticfiles.management.commands.runserver.Command object at 0x101981e50>>
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 91, in inner_run
self.validate(display_num_errors=True)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/base.py", line 266, in validate
num_errors = get_validation_errors(s, app)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/validation.py", line 30, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/loading.py", line 158, in get_app_errors
self._populate()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/loading.py", line 64, in _populate
self.load_app(app_name, True)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/loading.py", line 88, in load_app
models = import_module('.models', app_name)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/Users/Kinnovate/Desktop/fsdjango/platformsite/notices/models.py", line 9, in <module>
from common.fields import PickleField
File "/Users/Kinnovate/Desktop/fsdjango/platformsite/common/fields/__init__.py", line 1, in <module>
from pickle import *
File "/Users/Kinnovate/Desktop/fsdjango/platformsite/common/fields/pickle.py", line 27, in <module>
mysql_backend = settings.DATABASE_ENGINE == 'mysql'
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/functional.py", line 186, in inner
return func(self._wrapped, *args)
AttributeError: 'Settings' object has no attribute 'DATABASE_ENGINE'
this is the part of settings.py relevant to the question
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': os.path.join(DIRNAME, 'database.sqlite3'), # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
how do i fix this?
What is /Users/Kinnovate/Desktop/fsdjango/platformsite/common/fields/pickle.py? Is it your code? Then you have an error in it, because you really don't have DATABASE_ENGINE in your seetings. Use settings.DATABASES['default']['ENGINE'] instead.
You are missing something
Because as your backtrace your database must be mysql.
File "/Users/Kinnovate/Desktop/fsdjango/platformsite/common/fields/pickle.py", line 27, in <module>
mysql_backend = settings.DATABASE_ENGINE == 'mysql'
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/functional.py", line 186, in inner
return func(self._wrapped, *args)
Because its enter in mysql_backend = settings.DATABASE_ENGINE == 'mysql' line.
As per your settings its 'ENGINE': 'django.db.backends.sqlite3', so it must be enter in sqlite please check your app because it might be possible that your settings.py might be refer from another place.

Django--HELP. django not creating sqlite database file as expected

New to django
following tutorial 1. also looked up all related questions on stack overflow. thought it was a absolute path issue...but absolute path seems to be correct. below is settings.py. any ideas?
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'Users/Leerix/cars/carfilter/database/temp.db', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
Below is the error i'm getting. Been at this for several hours and cannot find the bug. any help is greatly appreciated. Thx
python manage.py syncdb
Traceback (most recent call last):
File "manage.py", line 9, in <module>
execute_from_command_line(sys.argv)
File "/Library/Python/2.5/site-packages/django/core/management/__init__.py", line 420, in execute_from_command_line
utility.execute()
File "/Library/Python/2.5/site-packages/django/core/management/__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Library/Python/2.5/site-packages/django/core/management/base.py", line 196, in run_from_argv
self.execute(*args, **options.__dict__)
File "/Library/Python/2.5/site-packages/django/core/management/base.py", line 232, in execute
output = self.handle(*args, **options)
File "/Library/Python/2.5/site-packages/django/core/management/base.py", line 371, in handle
return self.handle_noargs(**options)
File "/Library/Python/2.5/site-packages/django/core/management/commands/syncdb.py", line 57, in handle_noargs
cursor = connection.cursor()
File "/Library/Python/2.5/site-packages/django/db/backends/__init__.py", line 306, in cursor
cursor = self.make_debug_cursor(self._cursor())
File "/Library/Python/2.5/site-packages/django/db/backends/sqlite3/base.py", line 259, in _cursor
self.connection = Database.connect(**kwargs)
sqlite3.OperationalError: unable to open database file
Perhaps you meant to use an absolute path (one starting with /) instead of a relative path.
Delete the database file at that location. Also, the path starting with Users isn't absolute (is it?) make sure if you're on windows that it starts with a drive letter. (C:\)

Categories