Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

How to deploy django crud web application and database is postgress using different technology

How to deploy django crud web application and database is postgress in ubuntu

How to deploy django crud web application and database is postgress using docker container

How to deploy django crud application using docker in windows

Deploying a Django CRUD web application with a PostgreSQL database on Ubuntu involves several steps. Below is a step-by-step example to guide you through the process.

Step 1: Install Required Software
Python and Pip:

sudo apt update
sudo apt install python3 python3-pip
Enter fullscreen mode Exit fullscreen mode

PostgreSQL:

sudo apt install postgresql postgresql-contrib
Enter fullscreen mode Exit fullscreen mode

Step 2: Set Up PostgreSQL Database
Create a PostgreSQL User and Database:

sudo -u postgres psql
Enter fullscreen mode Exit fullscreen mode
CREATE DATABASE your_database;
CREATE USER your_user WITH PASSWORD 'your_password';
ALTER ROLE your_user SET client_encoding TO 'utf8';
ALTER ROLE your_user SET default_transaction_isolation TO 'read committed';
ALTER ROLE your_user SET timezone TO 'UTC';
GRANT ALL PRIVILEGES ON DATABASE your_database TO your_user;
\q
Enter fullscreen mode Exit fullscreen mode

Step 3: Set Up a Django Project
Create a Django Project:

mkdir your_project
cd your_project

python3 -m venv venv
source venv/bin/activate

pip install django
Enter fullscreen mode Exit fullscreen mode

Create a Django App:

django-admin startproject your_project .
python manage.py startapp your_app
Enter fullscreen mode Exit fullscreen mode

Step 4: Configure Django Settings
Open your_project/settings.py and update the database configuration:

# your_project/settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'your_database',
        'USER': 'your_user',
        'PASSWORD': 'your_password',
        'HOST': 'localhost',
        'PORT': '',
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Create Django Models
Open your_app/models.py and define your models. For example:

# your_app/models.py

from django.db import models

class Item(models.Model):
    name = models.CharField(max_length=255)

    def __str__(self):
        return self.name
Enter fullscreen mode Exit fullscreen mode

Step 6: Make Migrations and Apply

python manage.py makemigrations
python manage.py migrate
Enter fullscreen mode Exit fullscreen mode

Step 7: Create Django Views and Templates
Create views and templates for your CRUD operations. For example:

# your_app/views.py

from django.shortcuts import render, redirect
from .models import Item

def item_list(request):
    items = Item.objects.all()
    return render(request, 'your_app/item_list.html', {'items': items})

def item_create(request):
    if request.method == 'POST':
        name = request.POST['name']
        Item.objects.create(name=name)
        return redirect('item_list')
    return render(request, 'your_app/item_form.html')

# Create templates folder and add item_list.html and item_form.html
Enter fullscreen mode Exit fullscreen mode

Step 8: Configure URLs
Open your_app/urls.py and define your URLs:

# your_app/urls.py

from django.urls import path
from .views import item_list, item_create

urlpatterns = [
    path('items/', item_list, name='item_list'),
    path('items/create/', item_create, name='item_create'),
]
Enter fullscreen mode Exit fullscreen mode

Include these URLs in your_project/urls.py:

# your_project/urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('your_app.urls')),
]
Enter fullscreen mode Exit fullscreen mode

Step 9: Run the Django Development Server

python manage.py runserver
Visit http://127.0.0.1:8000/items/ in your browser to access the CRUD web application.

Step 10: Collect Static Files (for Production)

python manage.py collectstatic
Step 11: Configure a Production Web Server
For production, use a production-ready web server like Gunicorn and set up a reverse proxy (e.g., Nginx or Apache) for deployment.

This example provides a minimal setup. In a production environment, consider using more advanced configurations, adding authentication, and securing the PostgreSQL connection. Also, use environment variables for sensitive information.

How to deploy django crud web application and database is postgress using docker container

Deploying a Django CRUD web application with a PostgreSQL database using Docker containers involves several steps. Below is a step-by-step example to guide you through the process.

Step 1: Install Docker and Docker Compose
Install Docker:

sudo apt update
sudo apt install docker.io
sudo systemctl start docker
sudo systemctl enable docker
Enter fullscreen mode Exit fullscreen mode

Install Docker Compose:

sudo apt install docker-compose
Enter fullscreen mode Exit fullscreen mode

Step 2: Set Up a Django Project
Follow the steps from the previous example to set up a Django project, create a Django app, configure the PostgreSQL database, and configure Django models.

Step 3: Create a Dockerfile
Create a Dockerfile in your project's root directory:

# Use an official Python runtime as a parent image
FROM python:3.8-slim

# Set the working directory to /app
WORKDIR /app

# Copy the current directory contents into the container at /app
COPY . /app

# Install any needed packages specified in requirements.txt
RUN pip install --no-cache-dir -r requirements.txt

# Make port 8000 available to the world outside this container
EXPOSE 8000

# Define environment variable for production
ENV DJANGO_SETTINGS_MODULE=your_project.settings.production

# Run app.py when the container launches
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "your_project.wsgi:application"]
Enter fullscreen mode Exit fullscreen mode

Step 4: Create a Docker Compose File
Create a docker-compose.yml file in your project's root directory:

version: '3'

services:
  web:
    build: .
    command: bash -c "python manage.py migrate && gunicorn your_project.wsgi:application -b 0.0.0.0:8000"
    volumes:
      - .:/app
    ports:
      - "8000:8000"
    depends_on:
      - db
  db:
    image: postgres:12
    environment:
      POSTGRES_DB: your_database
      POSTGRES_USER: your_user
      POSTGRES_PASSWORD: your_password
    ports:
      - "5432:5432"
Enter fullscreen mode Exit fullscreen mode

Step 5: Update Django Settings
Open your settings.py and create a production configuration:

# your_project/settings/production.py

from .base import *

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'your-secret-key'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ['your-domain.com']

# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'your_database',
        'USER': 'your_user',
        'PASSWORD': 'your_password',
        'HOST': 'db',
        'PORT': '5432',
    }
}

# ... other production settings
Enter fullscreen mode Exit fullscreen mode

Step 6: Build and Run Docker Containers
Build and run your Docker containers using Docker Compose:

docker-compose up --build -d
Enter fullscreen mode Exit fullscreen mode

Step 7: Apply Migrations
Apply Django migrations to set up the database:

docker-compose exec web python manage.py migrate
Enter fullscreen mode Exit fullscreen mode

Step 8: Access the Django Web Application
Visit http://localhost:8000 in your browser to access the deployed Django CRUD web application.

This example provides a basic setup for deploying a Django CRUD web application with Docker containers. Adjust configurations, add security measures, and consider using environment variables for sensitive information in a production environment.

your_project/
|-- your_app/
|   |-- __init__.py
|   |-- admin.py
|   |-- apps.py
|   |-- migrations/
|   |   `-- __init__.py
|   |-- models.py
|   |-- tests.py
|   |-- views.py
|-- your_project/
|   |-- __init__.py
|   |-- asgi.py
|   |-- settings/
|   |   |-- __init__.py
|   |   |-- base.py
|   |   |-- development.py
|   |   |-- production.py
|   |-- urls.py
|   |-- wsgi.py
|-- Dockerfile
|-- docker-compose.yml
|-- requirements.txt
|-- manage.py
Enter fullscreen mode Exit fullscreen mode

Image description

Image description

How to deploy django crud application using docker in windows

Step 1: Install Docker Desktop on Windows
Download Docker Desktop:

Go to the official Docker website: Docker Desktop for Windows.
Click on the "Get Docker Desktop for Windows" button.
Install Docker Desktop:

Run the installer (Docker Desktop Installer.exe) you downloaded.
Follow the installation wizard instructions.
Ensure that you enable Hyper-V and Containers when prompted.
Start Docker Desktop:
refrence
Once installed, start Docker Desktop from the Start menu.
Step 2: Prepare Your Django Application
Make sure your Django application is Docker-ready. This typically involves creating a Dockerfile and a docker-compose.yml file.

Dockerfile:
Create a Dockerfile in your project root. This file defines the environment for your Django application.

# Use an official Python runtime as a parent image
FROM python:3.9

# Set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

# Set the working directory to /app
WORKDIR /app

# Copy the current directory contents into the container at /app
COPY . /app

# Install any needed packages specified in requirements.txt
RUN pip install --upgrade pip && pip install -r requirements.txt

# Make port 8000 available to the world outside this container
EXPOSE 8000

# Run app.py when the container launches
CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]
Enter fullscreen mode Exit fullscreen mode

docker-compose.yml and requirement.txt:

Create a docker-compose.yml file in your project root. This file defines how your Docker containers will work together.

version: '3'

services:
  web:
    build:
      context: .
      dockerfile: Dockerfile
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/app
    ports:
      - "8000:8000"
    depends_on:
      - db

  db:
    image: postgres:latest
    environment:
      POSTGRES_DB: mybooks
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: rkgmkgskg@123
Enter fullscreen mode Exit fullscreen mode

requirement.txt

Django==3.2.4
psycopg2-binary==2.9.1
Enter fullscreen mode Exit fullscreen mode

2. Update Django Settings:
Update your Django settings to use the environment variables for database connection. Update your settings.py file:

settings.py

import os

DATABASES = {
'default': {
'ENGINE':'django.db.backends.postgresql',
'NAME': 'mybooks',
'USER': 'postgres',
'PASSWORD': 'rkgmkgskg@123',

'PORT': '5432',

'HOST': 'localhost',

}
Enter fullscreen mode Exit fullscreen mode

3. Build and Run Docker Containers:
Open a terminal in the project directory and run the following commands:

# Build Docker images
docker-compose build

# Start Docker containers
docker-compose up
Enter fullscreen mode Exit fullscreen mode

This will build your Django application and start it along with a PostgreSQL database.

4. Access Your Django Application:
Visit http://localhost:8000 in your web browser. Your Django CRUD application should be accessible.

5. Stop Docker Containers:
When you're done, press Ctrl + C in the terminal where Docker is running, or run the following command to stop the containers:

docker-compose down
Enter fullscreen mode Exit fullscreen mode

These are basic steps, and you may need to customize them based on your specific project structure and requirements. Adjust the Dockerfile, docker-compose.yml, and Django settings according to your needs. Also, consider using environment files for sensitive information like database credentials.

myproject/
|-- myapp/
|   |-- __init__.py
|   |-- admin.py
|   |-- apps.py
|   |-- migrations/
|   |   |-- __init__.py
|   |-- models.py
|   |-- tests.py
|   |-- views.py
|-- myproject/
|   |-- __init__.py
|   |-- settings.py
|   |-- urls.py
|   |-- asgi.py
|   |-- wsgi.py
|-- static/
|-- templates/
|-- Dockerfile
|-- .dockerignore
|-- requirements.txt
|-- manage.py
Enter fullscreen mode Exit fullscreen mode

reference
reference

Top comments (0)