Django PostgreSQL Model Setup

To work with PostgreSQL in a Django project, you need to configure your Django settings and define your models. Here are the steps:

  1. Install PostgreSQL and psycopg2: Make sure PostgreSQL is installed on your system. Then, install the psycopg2 package, which allows Django to interact with PostgreSQL.
    pip install psycopg2-binary
    
  2. Configure Django settings: In your Django project’s settings.py file, configure the database settings to use PostgreSQL.
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql',
            'NAME': 'your_database_name',
            'USER': 'your_database_user',
            'PASSWORD': 'your_database_password',
            'HOST': 'localhost',  # Set to your PostgreSQL server address
            'PORT': '5432',       # Default PostgreSQL port
        }
    }
    
  3. Define your Django models: Create your models as usual in your Django app’s models.py file. Here is an example:
    from django.db import models
    
    class Product(models.Model):
        name = models.CharField(max_length=100)
        description = models.TextField()
        price = models.DecimalField(max_digits=10, decimal_places=2)
        created_at = models.DateTimeField(auto_now_add=True)
        updated_at = models.DateTimeField(auto_now=True)
    
        def __str__(self):
            return self.name
    
  4. Apply migrations: Run the following commands to create the necessary database tables for your models:
    python manage.py makemigrations
    python manage.py migrate
    
  5. Use the models: You can now use the models in your views, forms, and other parts of your Django project. For example, to create a new product in a view:
    from django.shortcuts import render
    from .models import Product
    
    def create_product(request):
        if request.method == 'POST':
            name = request.POST.get('name')
            description = request.POST.get('description')
            price = request.POST.get('price')
            product = Product(name=name, description=description, price=price)
            product.save()
            return render(request, 'success.html')
        return render(request, 'create_product.html')
    

By following these steps, you can set up and use PostgreSQL with your Django project.