-1

Django wants an existing database, which you configure in settings.

But how can I create a second database?

I will use PostgreSQL.

guettli
  • 25,042
  • 81
  • 346
  • 663
  • Does this solve [Create a Postgres database using python](https://stackoverflow.com/questions/34484066/create-a-postgres-database-using-python) ? – JPG Oct 28 '20 at 16:48

2 Answers2

1
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))

Note

The default connection must have sufficient permissions to create the database.

JPG
  • 82,442
  • 19
  • 127
  • 206
-1

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;
  • The OP asking about ***how to "create" a database***, not *how to "attach/link" a database* – JPG Oct 28 '20 at 16:58