5

Say I have this really rad database I'm using with Django, but for debugging purposes I want to use the default `db.sqlite3' database in setting.py if my rad database isn't found or users aren't able to easily set up the database.

How can I accomplish this task with Django?

2 Answers 2

5

The way I do this is as such:

In settings.py:

import dj_database_url # you'll need this in requirements.txt

DATABASES = {
    "default": dj_database_url.config(default='sqlite:///db.sqlite3'),
}

If the DATABASE_URL environment variable is set, as it will be in production (Heroku for me, but you can use a DATABASE_URL env variable anywhere) then use that. Otherwise, fall back to sqlite

Additionally, at the end of settings.py I have:

# Import optional local settings.  This must be at the END of this file.
try:
    from .local import *
except ImportError:
    pass

This way you can override the sqlite database in two ways: you can set the DATABASE_URL environment variable, or you can create a "local.py" file (exclude this from version control via .gitignore) that overrides it and other settings selectively. Why two ways? Primarily because most of the devs on my team are more comfortable managing a local settings file than environment variables.

I use this philosophy for all of my settings that might vary between dev and production, or that contain something I don't want in source control for any other reason.

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

Comments

4

You can set a database deppending of your debug var for example. In settings file:

if DEBUG:
//test database using sqlite
 DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'you_db_name.sqlite3'),
    }
 }
else:
   //here your prod database

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.