Inside a Django project, I have one app, otherapp, which hits a Postgres database on a remote server that contains scraped data. I have a second app, content, which hits a different Postgres database on the same remote server, and contains pages I'd like to have served through the Wagtail CMS.
I installed Wagtail locally using these instructions (I did not use the Wagtail installer). I got it working locally. Then, I did a pg_dump of the local database and did psql db2 < db2dumpfile.sql on the remote database server.
Each of the apps works fine locally in isolation, but I can't get them to work together. I thought I could use a database router to specify which database I want used to retrieve different types of data.
But, when I put the database router into the settings file, it starts to fail. How can I fix this? Do I need to declare wagtailcore somewhere else in the project?
settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'db1',
'USER': DB_USERNAME,
'PASSWORD': DB_PASSWORD,
'HOST': HOST,
'PORT': PORT
},
'CMS': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'db2',
'USER': DB_USERNAME,
'PASSWORD': DB_PASSWORD,
'HOST': HOST,
'PORT': PORT
}
}
DATABASE_ROUTERS = [ 'projectname.routers.FindRouter',]
routers.py:
import os
from django.conf import settings
import socket
class FindRouter(object):
def db_for_read(self, model, **hints) :
if model._meta.app_label == 'content' :
return 'CMS'
return None
def db_for_read(self, model, **hints):
if model._meta.app_label == 'content' :
return 'CMS'
return None
def db_for_write(self, model, **hints):
if model._meta.app_label == 'content' :
return 'CMS'
return None
def allow_relation(self, obj1, obj2, **hints):
if obj1._meta.app_label == 'content' or obj2._meta.app_label == 'content':
return True
return None
def allow_migrate(self, db, app_label, model=None, **hints):
if app_label == 'content' :
return db == 'CMS'
return None
This is the error I am getting when I do runserver:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/cms/
Django Version: 1.9
Python Version: 2.7.10
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'wagtail.wagtailforms',
'wagtail.wagtailredirects',
'wagtail.wagtailembeds',
'wagtail.wagtailsites',
'wagtail.wagtailusers',
'wagtail.wagtailsnippets',
'wagtail.wagtaildocs',
'wagtail.wagtailimages',
'wagtail.wagtailsearch',
'wagtail.wagtailadmin',
'wagtail.wagtailcore',
'modelcluster',
'compressor',
'taggit',
'otherapp',
'content']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
'wagtail.wagtailcore.middleware.SiteMiddleware',
'wagtail.wagtailredirects.middleware.RedirectMiddleware']
Traceback:
File "/Users/username/.virtualenvs/bail/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
123. response = middleware_method(request)
File "/Users/username/.virtualenvs/bail/lib/python2.7/site-packages/wagtail/wagtailcore/middleware.py" in process_request
11. request.site = Site.find_for_request(request)
File "/Users/username/.virtualenvs/bail/lib/python2.7/site-packages/wagtail/wagtailcore/models.py" in find_for_request
122. return Site.objects.get(hostname=hostname) # Site.DoesNotExist here goes to the final except clause
File "/Users/username/.virtualenvs/bail/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method
122. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/username/.virtualenvs/bail/lib/python2.7/site-packages/django/db/models/query.py" in get
381. num = len(clone)
File "/Users/username/.virtualenvs/bail/lib/python2.7/site-packages/django/db/models/query.py" in __len__
240. self._fetch_all()
File "/Users/username/.virtualenvs/bail/lib/python2.7/site-packages/django/db/models/query.py" in _fetch_all
1074. self._result_cache = list(self.iterator())
File "/Users/username/.virtualenvs/bail/lib/python2.7/site-packages/django/db/models/query.py" in __iter__
52. results = compiler.execute_sql()
File "/Users/username/.virtualenvs/bail/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
852. cursor.execute(sql, params)
File "/Users/username/.virtualenvs/bail/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
79. return super(CursorDebugWrapper, self).execute(sql, params)
File "/Users/username/.virtualenvs/bail/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
64. return self.cursor.execute(sql, params)
File "/Users/username/.virtualenvs/bail/lib/python2.7/site-packages/django/db/utils.py" in __exit__
95. six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/Users/username/.virtualenvs/bail/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
64. return self.cursor.execute(sql, params)
Exception Type: ProgrammingError at /cms/
Exception Value: relation "wagtailcore_site" does not exist
LINE 1: ...ge_id", "wagtailcore_site"."is_default_site" FROM "wagtailco...
^
I gave up and put the Wagtail tables back into the first database, and now the two parts of the application are working together fine.
Related
Hey guys I am trying to have 2 postgres databases in my django project, one to hold user data and the other to hold other contents, but I am getting this error when I try to run createsuperuser but I was able to run both makemigrations and migrate --database=users_db and the same for other db as well.
raise ImproperlyConfigured("settings.DATABASES is improperly configured. "
django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.
From the django documentation, they have mentioned that it is okay to leave the default dict blank.
If the concept of a default database doesn’t make sense in the context of your project, you need to be careful to always specify the database that you want to use. Django requires that a default database entry be defined, but the parameters dictionary can be left blank if it will not be used. To do this, you must set up DATABASE_ROUTERS for all of your apps’ models, including those in any contrib and third-party apps you’re using, so that no queries are routed to the default database.
This is settings.py
DATABASES = {
'default': {},
'users_db': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'users_db',
'USER': 'postgres',
'PASSWORD': 'Trial_user123',
'HOST':'127.0.0.1',
'PORT':'5432',
},
'content_db': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'content_II',
'USER': 'postgres',
'PASSWORD': 'Trial_user123',
'HOST':'127.0.0.1',
'PORT':'5432',
},
}
DATABASE_ROUTERS = ['personal.routers.db_routers.AuthRouter', 'personal.routers.db_routers.PersonalDBRouter', ]
This is the db_routers.py
class AuthRouter:
route_app_labels = {'sessions', 'auth', 'contenttypes', 'admin', 'accounts'}
def db_for_read(self, model, **hints):
if model._meta.app_label in self.route_app_labels:
return 'users_db'
return None
def db_for_read(self, model, **hints):
if model._meta.app_label in self.route_app_labels:
return 'users_db'
return None
def allow_relation(self, obj1, obj2, **hints):
if (
obj1._meta.app_label in self.route_app_labels or
obj2._meta.app_label in self.route_app_labels
):
return True
return None
def allow_migrate(self, db, app_label, model_name=None, **hints):
if app_label in self.route_app_labels:
return 'users_db'
return None
class PersonalDBRouter:
route_app_labels = {'actions', 'blog', 'token_blacklist', 'taggit', 'django_celery_beat', 'django_celery_results',}
def db_for_read(self, model, **hints):
if model._meta.app_label in self.route_app_labels:
return 'content_db'
return None
def db_for_read(self, model, **hints):
if model._meta.app_label in self.route_app_labels:
return 'content_db'
return None
def allow_relation(self, obj1, obj2, **hints):
if (
obj1._meta.app_label in self.route_app_labels or
obj2._meta.app_label in self.route_app_labels
):
return True
return None
def allow_migrate(self, db, app_label, model_name=None, **hints):
if app_label in self.route_app_labels:
return 'content_db'
return None
This is Account Manager and when I try to run createsuperuser, it shows an error in the line where create_user saves.
class MyAccountManager(BaseUserManager):
def create_user(self, email, username, first_name, last_name, password=None):
if not email:
raise ValueError('Users must have an email address')
if not username:
raise ValueError('Users must have a username')
if not first_name:
raise ValueError('Users must have a First Name') # check later
user = self.model(
email=self.normalize_email(email),
username=username,
first_name=first_name,
last_name=last_name,
)
user.set_password(password)
user.save(using="users_db")
return user
def create_superuser(self, email, username, first_name, last_name, password):
user = self.create_user(
email=self.normalize_email(email),
password=password,
username=username,
first_name=first_name,
last_name=last_name,
)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
I don't understand what's causing this error as I have already provided the engine value and cannot find the error. Can someone tell me where the issue is?
Thanks
UPDATE
TRACEBACK:
(myvenv) C:\Demo_1\mainsite>python manage.py createsuperuser --
database=users_db
Email: admin#test.com
Username: admin
First name: Admin
Last name: Test
Password:
Password (again):
Traceback (most recent call last):
File "C:\Demo_1\mainsite\manage.py", line 21, in <module>
main()
File "C:\Demo_1\mainsite\manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "C:\Users\danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
utility.execute()
File "C:\Users\danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 79, in execute
return super().execute(*args, **options)
File "C:\Users\danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 398, in execute
output = self.handle(*args, **options)
File "C:\Users\danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 189, in handle
self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
File "C:\Demo_1\mainsite\accounts\models.py", line 98, in create_superuser
user = self.create_user(
File "C:\Demo_1\mainsite\accounts\models.py", line 94, in create_user
user.save()
File "C:\Users\danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\base_user.py", line 67, in save
super().save(*args, **kwargs)
File "C:\Users\danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 726, in save
self.save_base(using=using, force_insert=force_insert,
File "C:\Users\danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 763, in save_base
updated = self._save_table(
File "C:\Users\danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 868, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "C:\Users\danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 906, in _do_insert
return manager._insert(
File "C:\Users\danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 1270, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "C:\Users\danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\compiler.py", line 1414, in execute_sql
with self.connection.cursor() as cursor:
File "C:\Users\danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "C:\Users\danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\base.py", line 259, in cursor
return self._cursor()
File "C:\Users\danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\dummy\base.py", line 20, in complain
raise ImproperlyConfigured("settings.DATABASES is improperly configured. "
django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.
Try to remove the using in the save:
def create_user(...):
...
user.save()
def create_superuser(...):
...
user.save()
EDIT:
Just noticed your routers don't have db_for_write (you wrote db_for_read twice):
def db_for_write(self, model, **hints):
if model._meta.app_label in self.route_app_labels:
return 'users_db'
return None
Set your DataBase like :-
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'users_db',
'USER': 'postgres',
'PASSWORD': 'Trial_user123',
'HOST': 'localhost',
'PORT': '5432',
}
'content_db': {
'NAME': 'django.db.backends.postgresql_psycopg2',
'NAME': 'content_II',
'USER': 'postgres',
'PASSWORD': 'Trial_user123',
'HOST': 'localhost',
'PORT': '5432',
}
}
You have to migrate both databases differently like :-
$ ./manage.py migrate --database=users_db
$ ./manage.py migrate --database=content_II
Create a superuser in different database like :-
./manage.py createsuperuser --database=users_db
I am using multiple databases in Django and connected default SQLite and PostgreSQL db in the settings.py.
setting.py :
DATABASE_ROUTERS = ['routers.db_routers.AppRouter']
DATABASE_APPS_MAPPING = {'product': 'postgres',}
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
},
'postgres': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'product',
'USER': 'postgres',
'PASSWORD':'password',
'HOST':'localhost'
}
}
And also made the db_routers.py in the routers folder:
class AppRouter:
"""
A router to control all database operations on models in the
product application.
"""
def db_for_read(self, model, **hints):
"""
Attempts to read user models go to postgres.
"""
if model._meta.app_label == 'product':
return 'postgres'
return 'default'
def db_for_write(self, model, **hints):
"""
Attempts to write user models go to postgres.
"""
if model._meta.app_label == 'product':
return 'postgres'
return 'default'
def allow_relation(self, obj1, obj2, **hints):
"""
Allow relations if a model in the user app is involved.
"""
if obj1._meta.app_label == 'product' or \
obj2._meta.app_label == 'product':
return True
elif 'product' not in [obj1._meta.app_label, obj2._meta.app_label]:
return True
return None
def allow_migrate(self, db, app_label, model_name=None, **hints):
"""
Make sure the auth app only appears in the 'product_db'
database.
"""
if app_label == 'product':
return db == 'postgres'
return None
here, it's model.py:
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2)
weight = models.DecimalField(max_digits=10, decimal_places=2)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
app_label = 'product'
def __str__(self):
return self.name
I have successfully made the tables by running python3 manage.py makemigrations but when I try to migrate using python3 manage.py migrate --database=postgres, I am getting this error: ProgrammingError: relation "product" does not exist. SELECT COUNT(*) AS "__count" FROM "product"And the table is also not present in PgAdmin.
migration.py of product:
# Generated by Django 3.2.5 on 2021-07-16 13:25
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Product',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('price', models.DecimalField(decimal_places=2, max_digits=10)),
('weight', models.DecimalField(decimal_places=2, max_digits=10)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
],
options={
'db_table': 'product',
'managed': False,
},
),
]
Error:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/api/product/
Django Version: 3.2.5
Python Version: 3.8.10
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'post',
'product']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback (most recent call last):
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
The above exception (relation "product" does not exist
LINE 1: ...product"."created_at", "product"."updated_at" FROM "product"
^
) was the direct cause of the following exception:
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/rest_framework/generics.py", line 239, in get
return self.list(request, *args, **kwargs)
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/rest_framework/mixins.py", line 46, in list
return Response(serializer.data)
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/rest_framework/serializers.py", line 745, in data
ret = super().data
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/rest_framework/serializers.py", line 246, in data
self._data = self.to_representation(self.instance)
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/rest_framework/serializers.py", line 663, in to_representation
return [
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/django/db/models/query.py", line 280, in __iter__
self._fetch_all()
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/django/db/models/query.py", line 1324, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/django/db/models/query.py", line 51, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1175, in execute_sql
cursor.execute(sql, params)
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/django/db/backends/utils.py", line 98, in execute
return super().execute(sql, params)
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/django/db/backends/utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/django/db/utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/rudrakshi/Desktop/Rose/assignment/env/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
Exception Type: ProgrammingError at /api/product/
Exception Value: relation "product" does not exist
LINE 1: ...product"."created_at", "product"."updated_at" FROM "product"
^
After running makemigrations and then migrate,
I run my server and when I hit the endpoint- 'api/product/' I got this error - relation "product" does not exist LINE 1: ...product"."created_at", "product"."updated_at" FROM "product"
Looking at your migration file you have 'managed': False,, what does this mean? It means that you don't want the migration system to manage this model. This means that running migrate will not cause the corresponding tables to be created in the database. Don't edit migration files unless you understand what you are doing!
Remove whatever changes you might have made to the migration file, especially that 'managed': False, and then run:
python manage.py migrate product zero --fake
This will cause Django to mark all migrations for the app "product" as unapplied. This is fine since it seems like this is your initial migration, otherwise you might have wanted to change zero to some migration name. Next run:
python manage.py migrate
I have this error for 2 days now I triyed everything in the other topics nothings works for me. The code of the app was written in linux, but i got the folder and connected it to my project as an app, in this project there is 3 apps that are connecting good to the database, only this one gives an error unable to open data base. I'm using Windows on Localhost, a friend triyed on windows and it's working for him, only for me not working.
Note : When I go to localhost:8000/admin I can see the model created on the database.
PLEASE HELP!
Django Version: 2.2.3
I have tryied to give permissions of the folder on it's proprieties to read and write, tryied to change path of DIR, I switched from sqlite3 to postgres, made full path in database and not full one, triyed all the recommandations on topics but still shows the error
Settings. py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'devee',
'USER': 'postgres',
'PASSWORD': 'thepasswordichoosed',
'HOST': 'localhost',
'PORT': '5432',
}
}
Environment:
Request Method: POST
Request URL: http://localhost:8000/result
Django Version: 2.2.3
Python Version: 3.7.3
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'dashboard',
'account',
'analyse']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "C:\Users\I500913\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\I500913\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\handlers\base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "C:\Users\I500913\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\handlers\base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\I500913\AppData\Local\Continuum\anaconda3\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "C:\Users\I500913\Desktop\Projets\final\analyse\views.py" in analyse_result
22. seo_score, report = scrapper(website)
File "C:\Users\I500913\Desktop\Projets\final\analyse\seo_scrapper.py" in scrapper
411. sbl = SafeBrowsingList(api_key)
File "C:\Users\I500913\AppData\Local\Continuum\anaconda3\lib\site-packages\gglsbl\client.py" in __init__
35. self.storage = SqliteStorage(db_path, timeout=timeout)
File "C:\Users\I500913\AppData\Local\Continuum\anaconda3\lib\site-packages\gglsbl\storage.py" in __init__
73. self.db = sqlite3.connect(db_path, timeout)
Exception Type: OperationalError at /result
Exception Value: unable to open database file
I am newbie to python and djanog.
I install django using.
Pip install django
Than I installed Mssql connector.
pip install django-mssql
than I run syncdb using this command.
python manage.py syncdb
It shows all tables are created but I didn't see any table in sql server management studio.
After that I tried to open Admin panal using http:// 127.0.0.1:8000/admin
it gives error.
ERROR
'DatabaseWrapper' object has no attribute 'Database'
Following is error:
Request Method: GET
Request URL: http:// 127.0.0.1:8000/admin
Django Version: 1.6.1
Exception Type: AttributeError
Exception Value: 'DatabaseWrapper' object has no attribute 'Database'
Exception Location: C:\Python27\lib\site-packages\django\db\utils.py in __exit__, line 86
Python Executable: C:\Python27\python.exe
Python Version: 2.7.6
SETTING.PY
DATABASES = {
'default': {
'NAME': 'dbexp',
'ENGINE': 'sqlserver_ado',
'HOST': '172.16.26.51\instance',
'USER': '****',
'PASSWORD': '******',
}
}
STACK TRACE
Environment:
Request Method: GET
Request URL: http: //127.0.0.1:8000/admin/
Django Version: 1.6.1
Python Version: 2.7.6
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
114. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\django\contrib\admin\sites.py" in wrapper
215. return self.admin_view(view, cacheable)(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapped_view
99. response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func
52. response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\contrib\admin\sites.py" in inner
192. if not self.has_permission(request):
File "C:\Python27\lib\site-packages\django\contrib\admin\sites.py" in has_permission
143. return request.user.is_active and request.user.is_staff
File "C:\Python27\lib\site-packages\django\utils\functional.py" in inner
213. self._setup()
File "C:\Python27\lib\site-packages\django\utils\functional.py" in _setup
298. self._wrapped = self._setupfunc()
File "C:\Python27\lib\site-packages\django\contrib\auth\middleware.py" in <lambda>
18. request.user = SimpleLazyObject(lambda: get_user(request))
File "C:\Python27\lib\site-packages\django\contrib\auth\middleware.py" in get_user
10. request._cached_user = auth.get_user(request)
File "C:\Python27\lib\site-packages\django\contrib\auth\__init__.py" in get_user
140. user_id = request.session[SESSION_KEY]
File "C:\Python27\lib\site-packages\django\contrib\sessions\backends\base.py" in __getitem__
47. return self._session[key]
File "C:\Python27\lib\site-packages\django\contrib\sessions\backends\base.py" in _get_session
173. self._session_cache = self.load()
File "C:\Python27\lib\site-packages\django\contrib\sessions\backends\db.py" in load
20. expire_date__gt=timezone.now()
File "C:\Python27\lib\site-packages\django\db\models\manager.py" in get
151. return self.get_queryset().get(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py" in get
301. num = len(clone)
File "C:\Python27\lib\site-packages\django\db\models\query.py" in __len__
77. self._fetch_all()
File "C:\Python27\lib\site-packages\django\db\models\query.py" in _fetch_all
854. self._result_cache = list(self.iterator())
File "C:\Python27\lib\site-packages\django\db\models\query.py" in iterator
220. for row in compiler.results_iter():
File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py" in results_iter
710. for rows in self.execute_sql(MULTI):
File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
781. cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\util.py" in execute
69. return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\util.py" in execute
53. return self.cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\utils.py" in __exit__
86. db_exc_type = getattr(self.wrapper.Database, dj_exc_type.__name__)
Exception Type: AttributeError at /admin/
Exception Value: 'DatabaseWrapper' object has no attribute 'Database'
For me I installed both django and django-mssql with pip. django was version 1.6 and django-mssql was version 1.4.
From the docs:
The current version of django-mssql supports Django 1.6.
django-mssql 1.4 supports Django 1.4 and 1.5.
I solved the problem with installing django-mssql from source. Download the source from bitbucket.
https://bitbucket.org/Manfre/django-mssql/get/default.zip or clone it with mercurial.
Then run the below command to install
> python setup.py install
Now check the version of django-mssql
> python
>>> import sqlserver_ado
>>> sqlserver_ado.__version__
u'1.5a'
I am not much aware of Django, but, I know SQL Server. From the connection file below:
'default': {
'NAME': 'dbexp',
'ENGINE': 'sqlserver_ado',
'HOST': '172.16.26.51\instance',
'USER': '****',
'PASSWORD': '******',
}
I assume dbexp is the database name, sqlserver_ado is the database Engine name, which is also the Instance name. So, the Engine should be sqlserver_ado\instance and the actual host name is either the [computer name]/IP(172.16.26.51).
I looked at the similar posts before entering this question. I am using Django 1.5, Python 3.3.2, and MySQL 5.6 / Connector.
I am new to Django/Python and working my way through basic tutorial. I created a MySQL database , sync a very simple model, and started basic web server.
I have added entries to the tables via the basic shell commands and everything worked fine.
However when I log into admin portal it immediately throws an exception.
The traceback I see on my browser when I successfully log into the admin portal is:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/
Django Version: 1.6
Python Version: 3.3.2
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'webmgr')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "C:\Python33\lib\site-packages\django\core\handlers\base.py" in get_response
114. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python33\lib\site-packages\django\contrib\admin\sites.py" in wrapper
215. return self.admin_view(view, cacheable)(*args, **kwargs)
File "C:\Python33\lib\site-packages\django\utils\decorators.py" in _wrapped_view
99. response = view_func(request, *args, **kwargs)
File "C:\Python33\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func
52. response = view_func(request, *args, **kwargs)
File "C:\Python33\lib\site-packages\django\contrib\admin\sites.py" in inner
197. return self.login(request)
File "C:\Python33\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func
52. response = view_func(request, *args, **kwargs)
File "C:\Python33\lib\site-packages\django\contrib\admin\sites.py" in login
330. return login(request, **defaults)
File "C:\Python33\lib\site-packages\django\views\decorators\debug.py" in sensitive_post_parameters_wrapper
75. return view(request, *args, **kwargs)
File "C:\Python33\lib\site-packages\django\utils\decorators.py" in _wrapped_view
99. response = view_func(request, *args, **kwargs)
File "C:\Python33\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func
52. response = view_func(request, *args, **kwargs)
File "C:\Python33\lib\site-packages\django\contrib\auth\views.py" in login
43. auth_login(request, form.get_user())
File "C:\Python33\lib\site-packages\django\contrib\auth\__init__.py" in login
83. request.session.cycle_key()
File "C:\Python33\lib\site-packages\django\contrib\sessions\backends\base.py" in cycle_key
277. self.create()
File "C:\Python33\lib\site-packages\django\contrib\sessions\backends\db.py" in create
40. self.save(must_create=True)
File "C:\Python33\lib\site-packages\django\contrib\sessions\backends\db.py" in save
63. obj.save(force_insert=must_create, using=using)
File "C:\Python33\lib\site-packages\django\db\transaction.py" in __exit__
298. connection.savepoint_commit(sid)
File "C:\Python33\lib\site-packages\django\db\backends\__init__.py" in savepoint_commit
249. self._savepoint_commit(sid)
File "C:\Python33\lib\site-packages\django\db\backends\__init__.py" in _savepoint_commit
203. self.cursor().execute(self.ops.savepoint_commit_sql(sid))
File "C:\Python33\lib\site-packages\django\db\backends\util.py" in execute
69. return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Python33\lib\site-packages\django\db\backends\util.py" in execute
53. return self.cursor.execute(sql, params)
File "C:\Python33\lib\site-packages\django\db\utils.py" in __exit__
86. db_exc_type = getattr(self.wrapper.Database, dj_exc_type.__name__)
Exception Type: AttributeError at /admin/
Exception Value: 'DatabaseWrapper' object has no attribute 'Database'
My settings file looks like:
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ''
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'webmgr',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'gymweb.urls'
WSGI_APPLICATION = 'gymweb.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'NAME': 'twntest',
'ENGINE': 'mysql.connector.django',
'USER': 'root',
'PASSWORD': '**********',
'OPTIONS': {
'autocommit': True,
},
}
}
"""
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
"""
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_URL = '/static/'
Reinstall django. Seems like you have installed django 1.5 on top of 1.4