top of page

How to connect to the PostgreSQL Database in Django



Hello everyone!!


In this article we are going to show you how to connect postgresql in django. PostgreSQL is a powerful and open source object relational database system. It has a wide range of uses and applications in the field of technology, also it has fast performance. Django has an SQLite3 database by default. PostgreSQL has the capability to handle the complex database. The integration of PostgreSQL with Django can improve production performance.


In this article you will learn how to connect a postgreSQL database to a django project. Also you will learn how to create a Virtual environment for a django project and how to edit your django project setting file and connect with postgreSQL database. So let's start.



Create Virtual Environment

First create an empty folder and open it in the visual studio. After creating the directory and opening it in the visual studio, create a virtual environment using “py -m venv env” command by selecting a new terminal. The final step is to activate the virtual environment. Then use ctrl + shift +p shortcut key and select python executable file from the folder just created by creating a virtual environment command.







Now open a new terminal. You will see that the virtual environment will be activated.



Installing Django and PostgreSQL


To install Django and postgreSQL just run the following command

  1. pip install django

  2. pip install psycopg2



Creating project and application in Django

Let's create our first project, which will only have one project in our project folder.


django-admin startproject postgresConn

As a result of the above command, the “postgreConn” project folder will be created in our project folder.



Now move the project folder using the following command.

cd postgreConn


Launch the application using the following command.

python manage.py startapp testdb


Now running the project to ensure that the out project is working correctly. Run the following command.


Python .\manage runserver



from django.shortcuts import render

# Create your views here.

# Create your views here.
def index(request):
    return render(request,"index.html")

Then create a new folder in testdb “templates”. In this folder contains all webpage related files html files.


testdb>templates>index.html


<!DOCTYPE html>
<html lang="en">
<head>
<title>Home</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {
  box-sizing: border-box;
  
}

body {
  font-family: Arial, Helvetica, sans-serif;
  background-color: rgb(201, 233, 233);
}


/* Style the header */
header {
  background-color: rgb(7, 89, 102);
  padding: 1px;
  text-align: center;
  font-size: 25px;
  color: white;
}

/* Create two columns/boxes that floats next to each other */
nav {
  float: left;
  width: 25%;
  height: 300px; /* only for demonstration, should be removed */
  background: rgb(137, 239, 239);
  padding: 20px;
}

/* Style the list inside the menu */
nav ul {
  list-style-type: none;
  padding: 0;
}

article {
  float: left;
  padding: 20px;
  width: 75%;
  background-color: #f1f1f1;
  height: 300px; /* only for demonstration, should be removed */
}

p4 {
  font-size: 12;
  background-color: blue;
}

/* Clear floats after the columns */
section::after {
  content: "";
  display: table;
  clear: both;
}

/* Style the footer */
footer {
  
  background-color: rgb(7, 89, 102);
  padding: 10px;
  text-align: center;
  color: white;
}

/* Responsive layout - makes the two columns/boxes stack on top of each other instead of next to each other, on small screens */
@media (max-width: 600px) {
  nav, article {
    width: 100%;
    height: auto;
  }
}

</style>
</head>
<body>

<h1>CodersArts</h1>
<p>Welcome to our website. Here you will find all sorts of information about our work as a Web Development, Mobile App Development, 
  Technology Solutions for Business, Hiring dedicated developer for Project, IT Solutions, Database Development, Programming expert 
  Help solutions. we provide all the programming expert  help, guidance, and support my clients need in order to get good grasp of 
  understanding and scaling business at the highest level . Take a look around and explore the various services we offer and some 
  examples of the kind of work we do.</p>
<header>
  <h2>Need Help In Programming Task?</h2>
</header>
<p font-size="12">Codersarts is trusted and top rated leading website for help in Programming Assignment, Coursework, Coding, and Project. 
  Get help from vetted software developers, engineers, ML Researchers and programming experts.</p>
<section>
  <nav>
    <ul>
      <div style="font-size:large">
      <li><a href="#">Machine Learning Assignment help</a></li>
      <li><a href="#">Deep Learning Assignment Help</a></li>
      <li><a href="#">NLP Assignment Help</a></li>
      <li><a href="#">Computer Vision Assignment Help</a></li>
      <li><a href="#">R Programming Assignment Help</a></li>
      <li><a href="#">Big Data Assignment Help</a></li>
    </div>
    </ul>
  </nav>
  
  <article>
    <h1>Assignments</h1>
    <div class="container">
      {% for x in obj %}
      <div class="row">
        <div style="text-align: left: ;;">
          {{x.assignment}} <a> : - </a> {{x.description}}
          
          <div>
            

        </div>
      </div>
      {% endfor %}
    </div>
  </article>
</section>

<footer>

 <p> Terms and Conditions        Privacy Policy    Pricing Policy       Refund Policy         COPYRIGHT © 2017 - 2022</p>
</footer>

</body>
</html>

postgreConn>postgreConn>urls.py


from django.contrib import admin
from django.urls import path
from testdb.views import index

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',index,name="index")
]

postgresConn>testdb>models.py


from django.db import models

# Create your models here.
class Assignment(models.Model):
    assignment=models.CharField(max_length=100)
    description = models.TextField()
    def __str__(self):
        return self.assignment 

postgresConn>testdb>admin.py


from django.contrib import admin

# Register your models here.
from .models import Assignment
admin.site.register(Assignment)

Now open pgadmin4. Create a database “test1"



postgreConn>settings.py


By default the django uses sqlite3 database. Here we change the code and field the details of database name, user and password to connect with postgresql.

DATABASES = {
    'default': {
       
        'ENGINE': 'django.db.backends.postgresql',
       'NAME': 'test1',
       'USER': 'pushkar',
       'PASSWORD': 'pushkar',
    }
}


Test Connection

Run the following command to migrate all tables in our Django project to PostgreSQL.


python .\manage.py makemigrations
python .\manage.py migrate

You will get the output as shown below.



Create Superuser

Just run this command to create superuser. field the details like username, email address and password.


python .\manage.py createsuperuser



Now run the Django project

command : python .\manage.py runserver




We go to on http://127.0.0.1:8000/admin/ and Add the assignment and descriptions by clicking on add button.



After adding the you will see it on the home page.



Conclusion : In this article We have successfully connect with PostgreSQL in Django


Need more help in Django Projects ?

  • Django Assignment help

  • Django Error Resolving Help

  • Mentorship in Django from Experts

  • Django Development Project

If you are looking for help in Django project contact us contact@codersarts.com


תגובות


bottom of page