0

How do I use a database connection URL in setting up database config in Django as opposed to using a dictionary? Instead of using:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': os.getenv('DB_NAME'),
        'USER': os.getenv('DB_USER'),
        'PASSWORD': os.getenv('DB_PASSWORD'),
        'PORT': os.getenv('DB_PORT'),
        'HOST': os.getenv('DB_HOST')
     }
 }

I want to use:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'postgresql://DB_USER:DB_PASSWORD@localhost:5432/DB_NAME'
     }
 }
2
  • 1
    There is no default way to do this, someone made dj-database-url which allows you to do exactly this. Commented Oct 25, 2019 at 11:00
  • Thank you Nico Griffioen. I will check out dj-database-url Commented Oct 25, 2019 at 12:37

1 Answer 1

1

This is how I added a database url to one of my django apps.

First, install this package

pip install dj-database-url

Next, add this line to your settings.py in your django project

...
DATABASES['default'] = dj_database_url.config(default=os.getenv('DATABASE_URI'))
...

In place of os.getenv('DATABASE_URI'), you can also explicitly mention your database url

You can refer here to the github repo for more configurations.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.