Django wants an existing database, which you configure in settings.
But how can I create a second database?
I will use PostgreSQL.
Django wants an existing database, which you configure in settings.
But how can I create a second database?
I will use PostgreSQL.
from django.db import connections
default_connection = connections['default']
no_db_connection = default_connection._nodb_connection
db_name = "ANY_DATABASE_NAME_123"
with no_db_connection.cursor() as cursor:
cursor.execute("CREATE DATABASE {dbname}".format(dbname=db_name))
The default connection must have sufficient permissions to create the database.
To add postgresql database in settings, add this code in settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'your_db_name',
'USER': 'user_name',
'PASSWORD': 'your_password',
'HOST': 'localhost',
'PORT': '5432',
}
}
Then run commands:
python manage.py makemigrations
python manage.py migrate
And if you want to create database, user and password, use these commands:
sudo -u postgres psql
postgres=# create database mydb;
postgres=# create user myuser with encrypted password 'mypass';
postgres=# grant all privileges on database mydb to myuser;