[Django]-Django: permission denied when trying to access database after restore (migration)

108👍

✅

It turns out that you should grant explicit ownership of all objects in the database to the owner after restore. The owner is not a superuser. It’s not enough to only set the owner at database creation time. The final solution for migration goes like this:

on the client:

pg_dump -f dump.sql -Ox database

on the server:

su postgres    
dropdb database
createdb database -O user
psql database -f dump.sql

and then to set the privileges:

psql database -c "GRANT ALL ON ALL TABLES IN SCHEMA public to user;"
psql database -c "GRANT ALL ON ALL SEQUENCES IN SCHEMA public to user;"
psql database -c "GRANT ALL ON ALL FUNCTIONS IN SCHEMA public to user;"

Note that we could’ve run the sql command in psql console but this form is easily embeddable in scripts and such.

2👍

Try to do this from postgres user:

sudo su - postgres
pg_dump -f dump.sql -Ox database

Or just pass -U flag:

pg_dump -f dump.sql -Ox database -U postgres

0👍

Here’s how I fixed mine. I saved myself a ton of a headache by simply changing the user to match the current logged in user of the destination server where the import will happen.

In my case, the imported db had a user of x (x was also the username for the machine it was running on), and the destination machine had a username of y, and a postgres user of y too.

Therefore, I simply changed the Database User and Password in my Django settings to match the destination machine’s y user details.

Then did this:

$ sudo -u postgres psql
psql > GRANT ALL PRIVILEGES DATABASE ON mydb TO y;

Sipping some kool-aid now!

Leave a comment