Connecting PostgreSQL with Django

Connecting postgreSQL with DJANGO

 To create your first Django project refer to this blog – Creating first Django Project

 

 

1. Install psycopg2: Django uses the psycopg2 library to interact with PostgreSQL databases. Make sure you have it installed. You can install it using pip:

				
					pip install psycopg2

				
			

 

 

 

2. Configure the settings: In your Django project, open the file helloworldproject/settings.py (or the name of your project) and find the DATABASES setting. Modify it to use PostgreSQL:

				
					DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'your_database_name',
        'USER': 'your_database_user',
        'PASSWORD': 'your_database_password',
        'HOST': 'localhost',  # Replace with your PostgreSQL host address if not local.
        'PORT': '',          # Set to empty string for the default port (usually 5432).
    }
}

				
			

Replace your_database_name, your_database_user, and your_database_password with your PostgreSQL database name, username, and password, respectively. If your PostgreSQL database is not hosted locally, change the HOST field to the appropriate address

 

 

 

 

3. Create the database: Before running the Django development server, you need to create the database you specified in the settings.py file. To do this, run the following command:

				
					python manage.py migrate

				
			

This will create all the necessary tables and structures in your PostgreSQL database.

 

 

 

After making changes to your models, you need to generate migration files that capture these changes. Run the following command in your terminal: 

				
					python manage.py makemigrations

				
			

 

 

 

4. Run the development server: Now, you can start the Django development server:

				
					python manage.py runserver

				
			

 

Your Django project is now connected to the PostgreSQL database. You can create models, perform database operations, and use Django’s ORM to interact with the PostgreSQL database seamlessly.

Tech Amplifier Final Logo