In my new Django project I set up a MongoDB database and use mongoengine module
but I can't properly access the dabase neither in shell nor in views.
"ConnectionError: You have not defined a default connection"
My settings.py includes the following:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'DaTaBaSe',
'USER': 'root',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '3306',
},
'tracking': {
'ENGINE': 'django.db.backends.dummy',
'NAME': 'analytics',
}
}
import mongoengine
SESSION_ENGINE = 'mongoengine.django.sessions'
mongoengine.connect(_MONGODB_NAME, 'localhost:27017')
AUTHENTICATION_BACKENDS = (
'mongoengine.django.auth.MongoEngineBackend',
)
In models.py:
import mongoengine
from mongoengine import *
from myproject.settings import _MONGODB_NAME
mongoengine.connect(_MONGODB_NAME, 'localhost:27017')
I have not tested this in-depth, but so far it worked for me:
mongoengine.connect('yourdb', alias='default')
In your settings.py file replace:
mongoengine.connect(_MONGODB_NAME, 'localhost:27017')
with the below code (notice the added 'host='):
mongoengine.connect(_MONGODB_NAME, host='localhost:27017')
To use django with MongoDB do not use the django package available on https://www.djangoproject.com and install other packages like mongoengine, if follow this process you will find lot of difficulties.
Rather you need to use the no#rel version of django that has been forked from djangoproject and added MongoDB support and I am sure it will make setup process and development process lot easier.
Follow this link to install and set up the django with MongoDB.
http://django-mongodb-engine.readthedocs.org/en/latest/topics/setup.html
One more thing you may find the error below, while setting up django.
"*Error on Django-nonrel and MongoDB: AutoField (default primary key) values must be strings representing an ObjectId on MongoDB (got u'1' instead). Please make sure your SITE_ID contains a valid ObjectId string.*"
Follow this link to fix.
https://gist.github.com/ielshareef/2986459
Please let me know if you need any more help on this.
Related
I am accessing the remote database in my Django project as follows:
settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
},
'remote_db' : {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'db_name',
'USER': 'db_user',
'PASSWORD': 'db_password',
'HOST': '192.*.*.*',
'PORT': '1433',
}
}
For accessing default database table's data, I use the following syntax:
from app_name.models import mymodel
mymodel.objects.all()
My remote database has tables like reports, emplayee_data, etc that are already there and my project has no models defined for these tables.
I need to access these tables and I am unsure how to perform this action.
remote_db.reports.all()
All in all, my main objective is to copy the data from remote_db to default database.
Note:
remote_db gets new data everyday.
I think you need to also define models for reports and employee_data in this project.
And then you can use them like the following:
reports.objects.using('remote_db').all()
You mentioned that there are no models defined for the tables. I think it will be a good option to make a script to fetch data from remote_db and add it to default. You will have to use raw SQL to do that if you don't create models for those tables. Another option would be getting the remote_db dump and importing it to the default database.
I've got a postgres DB which Django successfully connects to but when trying to create a new model I'm getting the error settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.
I know settings.DATABASES is correctly configured as I've already created models which then Django used to create tables in the DB but for whatever reason it is now causing this error.
You can also see that I have already "supplied the ENGINE value".
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': os.environ['POSTGRES_DB'],
'USER': os.environ['POSTGRES_USER'],
'PASSWORD': os.environ['POSTGRES_PASSWORD'],
'HOST': 'db',
'POST': '5432',
}
}
All help is appreciated.
Replace your ENGINE setting by:
'ENGINE': 'django.db.backends.postgresql'
It is the correct setting in Django 3 and up. See https://docs.djangoproject.com/en/3.0/internals/deprecation/#deprecation-removed-in-3-0.
Turns out I'm an idiot.
I'm using docker and I forgot that I need to enter the container to do DB migrations 🤦♂️
The exact cause of this error is that the dockerfile creates an environment variable called "DJANGO_SETTINGS_MODULE" which Django looks for and the value is the name of an alternate file to be used for settings. As I wasn't in the docker container, this environment variable wasn't available so it was using the default settings.py which has had its DB settings removed.
I have an existing PostgreSQL Database and I want to create APIs around it using Django Rest Framework. How do I display the tables in my Database as models in Django to further use them for the API?
First of all, you have to connect the existing DB with your Django application by following those instructions https://docs.djangoproject.com/en/3.1/ref/databases/#postgresql-notes or simply add the code below in your settings.py file
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'db_name',
'USER': 'db_user',
'PASSWORD': 'db_user_password',
'HOST': '',
'PORT': 'db_port_number',
}
}
Secondly, Django provides a powerful command which will help you out to inspect your existing DB models and save those models into your models.py file.
python manage.py inspectdb > models.py
In case that you need more information please read the official documentation https://docs.djangoproject.com/en/3.1/howto/legacy-databases/#auto-generate-the-models.
I'm creating a django web app that is going to be a database management portal for multiple databases. Because the web app will touch multiple databases, it doesn't make sense to have a default. However, when I run manage.py inspectdb I get an error saying that the ENGINE value isn't set on my database. It most definitely is.
Here's my DATABASES setting in settings.py
DATABASES = {
'default': {
},
'my_db': {
'NAME': 'my_db',
'USER': 'user',
'PASSWORD': 'pass',
'HOST': '192.168.0.255',
'PORT': '',
'ENGINE': 'sql_server.pyodbc',
'OPTIONS': {
'driver': 'ODBC Driver 13 for SQL Server',
},
},
}
If I run manage.py inspectdb using this setup I get this error:
settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.
This doesn't make sense to me, since it says in the documentation that 'default' can be a blank {}.
However, if I supply a dummy NAME and ENGINE variable to the default db, it seems to work fine for the default DB, but it ignores my_db.
If I set default to look at my_db's information I get a login error (so I know at least something is working right there, even if my creds are bad).
So, what am I getting wrong in my database setup here?
You need to specify a database for which you need to inspectdb
python manage.py inspectdb --database your_db_name
For more details see the docs
As stated in the title, I am using django-mongodb-engine and I am attempting to configure the native Django authentication framework. I've read some comments online that it should work out of the box sans some features. However, I couldn't find any tutorials and, furthermore, I am getting errors on trying to set it up on my own. The issue I'm having most certainly has to do with database permissions. I have included the Django middleware and apps per the Django docs. However, when I issue the syncdb command it fails with an error.
$ python manage.py syncdb
OperationFailure: database error: not authorized for query on MyDB.system.namespaces
settings.py
DATABASES = {
'default': {
'ENGINE': 'django_mongodb_engine',
'NAME': 'MyDB',
'USER': 'mySuperUser',
'PASSWORD': 'mypass',
'HOST': 'XXX.XXX.XXX.XXX',
'PORT': '',
},
# some other DBs
}
Mongo User Permissions
myDB> db.system.users.find()
{ "_id" : ObjectId("..."), "user" : "mySuperUser", "pwd" : "...", "roles" : [ "readWriteAnyDatabase", "userAdminAnyDatabase", "dbAdminAnyDatabase", "clusterAdmin" ] }
I'm not sure what other permissions I can grant this guy, and/or where else I need to create this user.
Any ideas?
After playing around, here is the solution. You must use the native mongo admin database. Thus, the required changes:
# settings.py
DATABASES = {
'default': {
'ENGINE': 'django_mongodb_engine',
'NAME': 'admin',
'USER': 'mySuperUser',
'PASSWORD': 'mypass',
'HOST': 'XXX.XXX.XXX.XXX',
'PORT': '',
},
# some other DBs
}
The user mySuperUser must naturally exist on the admin database. To be safe regarding authentication actions such as adding and removing users, I gave it the userAdminAnyDatabase privilege in mongo. The privileges are probably excessive, but I'd have to play with it to determine the proper scope of the required permissions. Here are the permissions:
// mongo
admin> db.system.users.find()
{ "_id" : ObjectId("..."), "pwd" : "...", "roles" : [ "readWriteAnyDatabase", "dbAdminAnyDatabase", "clusterAdmin", "userAdminAnyDatabase" ], "user" : "mySuperUser" }
Next, we can finally run the syncdb command:
$ python manage.py syncdb
Creating tables ...
You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no): yes
Username (leave blank to use 'someUser'):
Email address: someUser#user.com
Password:
Password (again):
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installing indices for admin.LogEntry model.
Installing indices for auth.Group_permissions model.
Installing indices for auth.Group model.
Installing indices for auth.User_groups model.
Installing indices for auth.User_user_permissions model.
Installing indices for auth.User model.
Installing indices for sessions.Session model.
Installed 0 object(s) from 0 fixture(s)
$
The problem for me was that I had not specified a SITE_ID in my settings.py. I did this:
./manage.py shell
>>>from django.contrib.sites.models import Site
>>>Site().save()
>>>Site.objects.all()[0].id
u'5391dbc22ebd1212246d50c4'
If you aren't 'django.contrib.sites' then I'm not sure why this would be a problem. Unless you had been using that module and already installed the collection/table to the database. In either case, this is how I got MongoDB to start working correctly again.
I encountered the same issue. My Mongo DB is hosted on MongoLab and I don't find any solutions to solve this error. Although that my user already exists in my DB, I don't want to use the admin database. Someone else has encountered the same problem or find a solution ?