πŸš€ Professional Django Project Setup Guide (with PostgreSQL, .env, Git, and venv)

Mahfuz HossainMahfuz Hossain
6 min read

I'm Mahfuz Hossain, a third-year IT student from Bangladesh, passionate about backend development.πŸ“˜This guide walks you through the steps to set up a professional Django project using industry best practices. It covers everything from project initialization, setting up Python virtual environments, managing secrets with .env, using environs for configuration, Git version control, and connecting PostgreSQL.

By following this guide, you can create a scalable, secure, and maintainable Django project - perfect for production and portfolio use.

πŸ”§ Tools & Requirements

  • Python (β‰₯ 3.9)

  • PostgreSQL (Download from here)

  • Git for Windows

  • Code Editor (e.g., VS Code)

πŸ“ 1. Project Initialization

Create Project Directory

First, you need to create a dedicated directory for your Django project. This helps keep everything organized. Let’s start by creating the project folder and initializing Git.

mkdir myproject
cd myproject
git init

βœ… Create a .gitignore File

This file tells Git which files/folders to ignoreβ€”such as the virtual environment, .env file, and compiled files:

touch .gitignore

Paste the following content into .gitignore:

__pycache__/
*.py[cod]
*.sqlite3
db.sqlite3
*.log
.venv/
.env
/staticfiles

πŸ›  2. Set Up Python Virtual Environment

πŸ§ͺ What is a virtual environment?

A virtual environment is a self-contained Python workspace that isolates your project’s dependencies. This prevents conflicts between projects.

βœ… How to Set It Up:

python3 -m venv .venv
source .venv/bin/activate    # On Windows: .venv\Scripts\activate

Why use virtualenv?

  • Avoids version conflicts between projects.

  • Keeps your project lightweight and reproducible.

  • Industry-standard practice for Python apps.

πŸ“¦ 3. Install Django and Dependencies

βœ… For PostgreSQL Projects:

pip install django environs psycopg2-binary
  • django: Core web framework.

  • environs: Simplifies working with environment variables.

  • psycopg2-binary: PostgreSQL driver.

βœ… For SQLite (Default):

pip install django environs

🌿 What is environs?

environs is a lightweight Python library that helps you read and validate environment variables easily and safely from a .env file.

βœ… Save Dependencies

pip freeze > requirements.txt

This creates a list of all installed packages so others can install the exact same environment with:

pip install -r requirements.txt

βš™οΈ 4. Start Django Project

Create the main Django project structure.

django-admin startproject myproject .

The . ensures it doesn't nest the project in an extra folder.

πŸ“‚ The Project Structure Will Look Like:

myproject/
β”œβ”€β”€ .git/
β”œβ”€β”€ .gitignore
β”œβ”€β”€ .env
β”œβ”€β”€ .venv/
β”œβ”€β”€ myproject/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ asgi.py
β”‚   β”œβ”€β”€ settings.py
β”‚   β”œβ”€β”€ urls.py
β”‚   └── wsgi.py
β”œβ”€β”€ manage.py
└── requirements.txt

πŸ” 5. Set Up .env and Use environs

βœ… Create .env File

DEBUG=True
SECRET_KEY=your-secret-key
DATABASE_NAME=yourdbname
DATABASE_USER=yourdbuser
DATABASE_PASSWORD=yourdbpassword
DATABASE_HOST=localhost
DATABASE_PORT=5432  # for mysql 3306

πŸ”’ Why is .env important?

βœ… Keeps sensitive data out of your code

You don’t want your secret keys, passwords, or API keys visible in settings.py. Instead, you store them in .env and load them safely using libraries like environ

βœ… Modify settings.py to Load .env Variables

Edit config/settings.py:

from environs import Env

env = Env()
env.read_env()

SECRET_KEY = env.str("SECRET_KEY")
DEBUG = env.bool("DEBUG", default=False)

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': env.str("DATABASE_NAME"),
        'USER': env.str("DATABASE_USER"),
        'PASSWORD': env.str("DATABASE_PASSWORD"),
        'HOST': env.str("DATABASE_HOST"),
        'PORT': env.str("DATABASE_PORT"),
    }
}

For SQLite, you can skip database env variables and use:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

🌐 6. Push Project to GitHub

βœ… Version Control Commands

git add .
git commit -m "Initial commit"
git branch -M main
git remote add origin https://github.com/yourusername/myproject.git
git push -u origin main

Why GitHub?

  • Share code with others

  • Maintain version history

  • Easily deploy from GitHub on platforms like Heroku, Vercel, or Render

πŸ§ͺ 7. Run Migrations & Test Project

Migrations sync your models with the database.

python manage.py migrate
python manage.py runserver

Visit http://127.0.0.1:8000 β€” You should see the Django welcome page.

🧩 8. Add Home Page to Confirm Setup

βœ… Create a Django App

python manage.py startapp myapp

Add 'myapp' to INSTALLED_APPS in settings.py.

βœ… Add a Simple View

myapp/views.py:

from django.http import HttpResponse

def home(request):
    return HttpResponse("<h1> Welcome to the Professional Django Setup! </h1>")

βœ… Create App URL and Hook It In

myapp/urls.py:

from django.urls import path
from .views import home

urlpatterns = [
    path('', home, name='home'),
]

myproject/urls.py:

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myapp.urls')),
]

πŸ›’ 9. Other Database Notes

SQLite: Default, no setup needed.

PostgreSQL: Preferred in production.

MySQL:

pip install mysqlclient
'django.db.backends.mysql'

βœ… 10. Final Testing

Run the server and visit http://127.0.0.1:8000

You should see:

This confirms your environment is ready! 🎯

πŸ“ Summary Notes

  • Use .venv to isolate Python packages.

  • Use .env for secrets and environs to safely load them.

  • Use PostgreSQL for serious projects.

  • Use git and GitHub to track changes and collaborate.

  • Create a homepage to verify setup works.

🎁Bonus: Add a Beautiful Template Page

Replace the homepage with a rendered template:

myapp/views.py

from django.shortcuts import render

def home(request):
    return render(request, 'myapp/home.html')

myapp/templates/myapp/home.html

Create folders if needed. Then paste:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Django Project Ready</title>
  <style>
    body {
      font-family: 'Segoe UI', sans-serif;
      background-color: #f4f4f4;
      text-align: center;
      margin-top: 15%;
    }
    h1 { color: #2c3e50; font-size: 3em; }
    p { color: #34495e; font-size: 1.3em; }
  </style>
</head>
<body>
  <h1>πŸŽ‰ Django Setup Complete!</h1>
  <p>Your project is professionally configured and ready to build.</p>
</body>
</html>

Make Sure Template Path Works in settings.py:

Django will auto-discover templates if the folder structure is correct:

myapp/
β”œβ”€β”€ templates/
β”‚   └── myapp/
β”‚       └── home.html

You should see:

Again run the server and visit http://127.0.0.1:8000

🎯 You're Ready!

You now have a clean, secure, and production-ready Django setup

πŸ—‚ Final Project Structure

Here’s what your project should now look like:

myproject/
β”œβ”€β”€ .git/                         # Git repository
β”œβ”€β”€ .gitignore                    # Git ignore rules
β”œβ”€β”€ .env                          # Environment variables (NOT in Git)
β”œβ”€β”€ .venv/                        # Virtual environment folder (NOT in Git)
β”œβ”€β”€ myproject/                    # Main Django project directory
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ asgi.py
β”‚   β”œβ”€β”€ settings.py               # Modified to use `environs`
β”‚   β”œβ”€β”€ urls.py                   # Includes `myapp.urls`
β”‚   └── wsgi.py
β”œβ”€β”€ manage.py                     # Django's CLI entry point
β”œβ”€β”€ myapp/                        # Django app folder
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ admin.py
β”‚   β”œβ”€β”€ apps.py
β”‚   β”œβ”€β”€ migrations/
β”‚   β”‚   └── __init__.py
β”‚   β”œβ”€β”€ models.py
β”‚   β”œβ”€β”€ tests.py
β”‚   β”œβ”€β”€ urls.py                  # Created for app routing
β”‚   β”œβ”€β”€ views.py                 # Contains the home view
β”‚   └── templates/
β”‚       └── myapp/
β”‚           └── home.html        # Your amazing homepage
└── requirements.txt             # (Optional but recommended)

πŸ™Œ Thank you for reading!
If you found this guide helpful, please consider following my blog for more developer-focused content.
Feel free to share your thoughts, questions, or suggestions in the comments as your feedback means a lot! πŸ’»

0
Subscribe to my newsletter

Read articles from Mahfuz Hossain directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Mahfuz Hossain
Mahfuz Hossain