How to create and restore Django database

Hi coders!

We really want to protect our Django database from getting attacked or some sort of database corruption especially after the deployment.

I will explain how to easily create a Django database backup and restore the database by using Django dbbackup library.

Installing django-dbbackup

First, let’s take a quick look at this django-dbbackup.

Then, let’s use the command below to install the library.

pip install django-dbbackup


#If you want to keep the dependency in the text.
pip freeze > requirements.txt

Next, let django know that we added the dbbackup library in the Django project file > settings.py.

We also want to add the detabase backup output location as well.

INSTALLED_APPS = (
    ...
    'dbbackup',  # django-dbbackup
)

DBBACKUP_STORAGE = 'django.core.files.storage.FileSystemStorage'
DBBACKUP_STORAGE_OPTIONS = {'location': '/my/backup/dir/'}

We can modify the storage option like this.

It will create a “dump” folder in the same django application path.

DBBACKUP_STORAGE = 'django.core.files.storage.FileSystemStorage'
DBBACKUP_STORAGE_OPTIONS = {'location': BASE_DIR/'dump'}
Django dbbackup

We can create a “dump” directly in the stated file path in the settings.py.

Use command to create a backup

Now we are ready to take a database backup file from command line.

Let’s use this command to create a backup file.

python manage.py dbbackup
Django database backup

Now we can confirm that we have a database backup file.

Restore database from the backup

Let’s use the backup file to restore the django database.

Django Admin panel

Let’s add a sample record to see if it changes after restoring to the empty database file.

To restore, we can use this command below.

python manage.py dbrestore
python manage.py dbrestore

Now, we can confirm the database is restored.
Congratulations!