Django Setup & Deployment Guide

1. Create the Django Project

  1. Open VS Code and open the terminal (View > Terminal).
  2. Navigate to your desired directory:
    • macOS/Linux:
    • cd '/Users/davidhearl/Documents/08 - Programming/GitHub'
    • Windows:
    • cd "C:\Users\davidhearl\iCloudDrive\Documents\Programming\GitHub"
  3. Create the project directiory
  4. mkdir myproject
    cd myproject
  5. Create a virtual environment:
  6. python -m venv virtual_environment
  7. Activate the virtual environment:
  8. Optional: Upgrade pip to the latest version to avoid warnings and improve package management:
  9. python -m pip install --upgrade pip
  10. Install Django and save requirements:
  11. pip install Django
    pip freeze > requirements.txt
  12. Create a new Django project:
  13. django-admin startproject myproject .
  14. Migrate changes
  15. python3 manage.py migrate
  16. Optional: Open the project in Visual Studio Code:
  17. code .

    Note: This requires the 'code' command to be installed in your PATH.

  18. Navigate into your project:
  19. cd myproject
  20. Run the development server:
  21. python3 manage.py runserver

2. Create a Django App

  1. Create the app:
  2. python manage.py startapp myapp
  3. Open the settings.py
  4. Add 'myapp' to INSTALLED_APPS in settings.py.
  5. INSTALLED_APPS = [
        ...
        'myapp',
    ]
  6. Create a superuser:
    python manage.py createsuperuser

3. Django Settings to Change

Edit myproject/settings.py:

4. Link the Project to GitHub

  1. Initialize a Git repository:
  2. git init
  3. Create a .gitignore file in the project root and add:
  4. touch .gitignore
  5. Add items to the .gitignore files
  6. virtual_environment/
    __pycache__/
    *.pyc
    *.sqlite3
    .env
    .code
  7. Install GitHub CLI
  8. Login to GitHub
  9. gh auth login
  10. Initialize Git and make the first commit:
  11. git add .
    git commit -m "Initial commit"
  12. Create a new private or public repository on GitHub from the terminal:
  13. gh repo create your-repo-name --public --source=. --remote=origin --push

    This creates the repo, links it, and pushes your code in one step.

  14. Optional: Rename branch to main if needed:
  15. git branch -M main
    git push -u origin main

5. Setting up the MVT

  1. Create the first view in myapp/views.py:
  2. from django.shortcuts import render
            
    def home(request):
        return render(request, 'myapp/home.html')
  3. Create the app-specific templates/myapp directory and home.html:
  4. mkdir -p myapp/templates/myapp
    touch myapp/templates/myapp/home.html
  5. Update settings.py to look for templates in the project root:
  6. TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [BASE_DIR / 'templates'],
            ...
        },
    ]
  7. Create a static directory and a CSS file for styling:
  8. mkdir -p static/css
    touch static/css/styles.css
  9. Make sure settings.py is configured to find static files:
  10. STATIC_URL = '/static/'
    STATICFILES_DIRS = [BASE_DIR / 'static']
  11. Create myapp/urls.py and define the route:
  12. touch myapp/urls.py
    from django.urls import path
    from . import views
    
    urlpatterns = [
        path('', views.home, name='home'),
    ]
  13. Include the app URLs in your project-level urls.py:
  14. from django.contrib import admin
    from django.urls import path, include
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('', include('myapp.urls')),
    ]

6. Common Django Commands

python manage.py runserver
python manage.py makemigrations
python manage.py migrate
python manage.py startapp appname
python manage.py createsuperuser
python manage.py shell
python manage.py collectstatic
python manage.py check

Deploying a Django Application on Debian

1. System Update and Dependencies

sudo apt update && sudo apt upgrade -y
sudo apt install python3 python3-pip python3-venv git curl build-essential libpq-dev -y

2. Create a Dedicated User (Optional)

sudo adduser django
sudo usermod -aG sudo django
su - django

3. Clone Your Django Project

git clone https://github.com/yourusername/yourproject.git
cd yourproject

4. Set Up Python Virtual Environment

python3 -m venv venv
source venv/bin/activate
pip install --upgrade pip
pip install -r requirements.txt

5. Configure Django for Production

python manage.py collectstatic
python manage.py migrate

6. Create Gunicorn Systemd Service

[Unit]
Description=gunicorn daemon for Django project
After=network.target

[Service]
User=django
Group=www-data
WorkingDirectory=/home/django/yourproject
ExecStart=/home/django/yourproject/venv/bin/gunicorn --workers 3 --bind unix:/home/django/yourproject/gunicorn.sock yourproject.wsgi:application

[Install]
WantedBy=multi-user.target
sudo systemctl start gunicorn
sudo systemctl enable gunicorn

7. Install and Configure Nginx

sudo apt install nginx -y
server {
    listen 80;
    server_name your.server.ip.or.domain;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/django/yourproject;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/home/django/yourproject/gunicorn.sock;
    }
}
sudo ln -s /etc/nginx/sites-available/yourproject /etc/nginx/sites-enabled
sudo nginx -t
sudo systemctl restart nginx

8. Adjust Firewall (If Needed)

sudo ufw allow 'Nginx Full'

9. Set Up HTTPS with Certbot (Optional)

sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d yourdomain.com

10. Final Checks