Django Tutorial · PostgreSQL

Connect to Database

Learn all about Connect to Database in this comprehensive tutorial.

5 min read advanced
  • To make Django able to connect to your database, you have to specify it in the DATABASES tuple in the settings.
  • As you can see in the settings.
  • The database does not have a name, but you have to assign one in order to access the database.
  • Insert the username and password that you specified when you created the database.
  • As you can see in the settings.
  • Once we have done the changes in settings.

Modify Settings

To make Django able to connect to your database, you have to specify it in the DATABASES tuple in the settings.py file.

Before, it looked like this:

Now, you should change it to look like this:

Note: Note: The values will be different for your project.

Engine?

As you can see in the settings.py file, we insert postgresql instead of sqlite.

Name?

The database does not have a name, but you have to assign one in order to access the database.

If no name is given, the provider accepts 'postgres' as the name of the database.

Username and Password?

Insert the username and password that you specified when you created the database.

Host? Port?

As you can see in the settings.py file, we insert postgresql instead of sqlite, and insert the username and password that we specified when we created the database.

The HOST and PORT can be found under the "Connectivity & security" section in the RDS instance. They are described as "Endpoint" and "Port":

Which for my project is this:

'HOST': 'w3-django-project.cdxmgq9zqqlr.us-east-1.rds.amazonaws.com'

'PORT': '5432'

Migrate

Once we have done the changes in settings.py, we must run a migration in our virtual environment, before the changes will take place:

python

Which will give you this result:

python

Now, if you run the project:

python

And view it in your browser: 127.0.0.1:8000/.

You will get the home page of the project, but if you click on the "members" link, you will see that there are no members.

That is because the database is empty. In the next chapter we will fill the database with members.

Module quiz

2 questions
1

Which of the following is true about Connect to Database?

2

What is the most common pitfall when working with Connect to Database?

Answer all questions to submit.