DEV Community

Tommi k Vincent
Tommi k Vincent

Posted on

How to create a database,user and grant privileges in Postgresql Python-Django.

step1:
Launch the SQL Shell by running postgres -u psql, provide the login details, and execute the below-provided command to create a new user:

CREATE USER master WITH PASSWORD '1234';
Enter fullscreen mode Exit fullscreen mode

Image description
you can verify user creation by running “\du” command and see below :

Image description
output signifies user named master has successfully been created.

step2: creating a database use the below command:

postgres=# CREATE DATABASE django;
Enter fullscreen mode Exit fullscreen mode

Image description
To verify the database creation, use the “\l” command:

Image description

The output snippet demonstrates that a new database named “django” has been successfully created

step3: Grant All Privileges/Access to the User/Role.
Finally, execute the “GRANT ALL PRIVILEGES” command to grant all the database privileges to the user, such as creating a database.

GRANT ALL PRIVILEGES ON DATABASE "django" to master;
Enter fullscreen mode Exit fullscreen mode

Image description
The output shows that the permissions have been successfully granted to the user.

Conclusion
In PostgreSQL, the CREATE USER statement with “PASSWORD” attributes creates a new user with login privileges. While the “CREATE DATABASE” command creates a new database. However, the newly created user can’t access or modify the database objects, such as tables, functions, views, etc. until the user is granted privileges on the database objects. To fulfill this purpose, the “GRANT ALL” statement is used in Postgres. This post presented a comprehensive guide on creating a new user, a database, and granting/assigning the database privileges to the newly created user.

Top comments (0)