DEV Community

ngemuantony
ngemuantony

Posted on • Edited on

Part 7: Deploying to PythonAnywhere

Introduction

In this final part, we'll walk through deploying our Django Project Budget Manager to PythonAnywhere, a popular platform for hosting Python web applications. We'll cover each step in detail to ensure a smooth deployment process.

Prerequisites

  1. Create a PythonAnywhere account:

  2. Prepare your project:

   # Create requirements.txt
   pip freeze > requirements.txt

   # Create runtime.txt (specify Python version)
   echo "python-3.9" > runtime.txt
Enter fullscreen mode Exit fullscreen mode

Step 1: Configure Production Settings

Create a production settings file:

# config/settings/production.py

from .base import *

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

# Allow only your PythonAnywhere domain
ALLOWED_HOSTS = ['yourusername.pythonanywhere.com']

# Security settings
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_CONTENT_TYPE_NOSNIFF = True
X_FRAME_OPTIONS = 'DENY'

# Static files configuration
STATIC_ROOT = '/home/yourusername/project_budget/staticfiles'
MEDIA_ROOT = '/home/yourusername/project_budget/media'

# Database configuration (using MySQL on PythonAnywhere)
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'yourusername$project_budget',
        'USER': 'yourusername',
        'PASSWORD': 'your-mysql-password',
        'HOST': 'yourusername.mysql.pythonanywhere-services.com',
        'OPTIONS': {
            'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
        },
    }
}

# Email configuration (using SMTP)
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'your-email@gmail.com'
EMAIL_HOST_PASSWORD = 'your-app-specific-password'
Enter fullscreen mode Exit fullscreen mode

Step 2: Upload Project to PythonAnywhere

  1. Open a Bash console on PythonAnywhere and clone your repository:
   # Navigate to home directory
   cd ~

   # Clone your repository
   git clone https://github.com/yourusername/project_budget.git

   # Create virtual environment
   mkvirtualenv --python=/usr/bin/python3.9 project_budget

   # Activate virtual environment
   workon project_budget

   # Install dependencies
   pip install -r project_budget/requirements.txt
Enter fullscreen mode Exit fullscreen mode
  1. Create necessary directories:
   mkdir ~/project_budget/staticfiles
   mkdir ~/project_budget/media
Enter fullscreen mode Exit fullscreen mode

Step 3: Configure PythonAnywhere Web App

  1. Go to the Web tab in PythonAnywhere dashboard

  2. Click "Add a new web app" and choose:

    • Your domain name (e.g., yourusername.pythonanywhere.com)
    • Python version (3.9)
    • Manual configuration
  3. Configure the virtual environment:

    • Virtual environment path: /home/yourusername/.virtualenvs/project_budget
  4. Configure WSGI file (/var/www/yourusername_pythonanywhere_com_wsgi.py):

   import os
   import sys

   # Add project directory to Python path
   path = '/home/yourusername/project_budget'
   if path not in sys.path:
       sys.path.append(path)

   # Set environment variables
   os.environ['DJANGO_SETTINGS_MODULE'] = 'config.settings.production'
   os.environ['SECRET_KEY'] = 'your-secret-key'

   # Initialize Django
   from django.core.wsgi import get_wsgi_application
   application = get_wsgi_application()
Enter fullscreen mode Exit fullscreen mode
  1. Configure static files in the Web tab:
    • URL: /static/
    • Directory: /home/yourusername/project_budget/staticfiles
  • URL: /media/
  • Directory: /home/yourusername/project_budget/media

Step 4: Set Up Database

  1. Go to the Databases tab and create a MySQL database:
   CREATE DATABASE yourusername$project_budget CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
Enter fullscreen mode Exit fullscreen mode
  1. Set a password for your MySQL database

  2. Apply migrations:

   cd ~/project_budget
   python manage.py migrate
Enter fullscreen mode Exit fullscreen mode
  1. Create a superuser:
   python manage.py createsuperuser
Enter fullscreen mode Exit fullscreen mode

Step 5: Collect Static Files

python manage.py collectstatic
Enter fullscreen mode Exit fullscreen mode

Step 6: Final Configuration

  1. Set up environment variables in the Web tab:

    • Click on the "Environment variables" section
    • Add the following variables:
     DJANGO_SETTINGS_MODULE=config.settings.production
     SECRET_KEY=your-secret-key
     DATABASE_URL=mysql://yourusername:password@yourusername.mysql.pythonanywhere-services.com/yourusername$project_budget
    
  2. Enable HTTPS:

    • In the Web tab, enable "Force HTTPS"
  3. Reload your web app

Testing the Deployment

  1. Visit your site at https://yourusername.pythonanywhere.com

  2. Test the following:

    • User registration and login
    • Project creation and management
    • File uploads
    • Email functionality

Common Issues and Solutions

  1. Static files not loading

    • Check STATIC_ROOT and MEDIA_ROOT paths
    • Run collectstatic again
    • Verify static files configuration in Web tab
  2. Database connection errors

    • Verify database credentials
    • Check database configuration in settings
    • Ensure MySQL server is running
  3. 500 Server Error

    • Check error logs in the Web tab
    • Verify WSGI file configuration
    • Check permissions on media and static directories
  4. Email not working

    • Verify email settings
    • Check if your email provider allows SMTP
    • Use app-specific password for Gmail

Maintenance Tasks

  1. Updating the application:
   # Pull latest changes
   cd ~/project_budget
   git pull

   # Activate virtual environment
   workon project_budget

   # Install new dependencies
   pip install -r requirements.txt

   # Apply migrations
   python manage.py migrate

   # Collect static files
   python manage.py collectstatic

   # Reload web app from PythonAnywhere dashboard
Enter fullscreen mode Exit fullscreen mode
  1. Backing up data:
   # Backup database
   python manage.py dumpdata > backup.json

   # Backup media files
   zip -r media_backup.zip media/
Enter fullscreen mode Exit fullscreen mode

Security Considerations

  1. Keep secrets secure:

    • Never commit sensitive data to version control
    • Use environment variables for secrets
    • Regularly rotate passwords and keys
  2. Regular updates:

    • Keep Django and other packages updated
    • Monitor security advisories
    • Apply security patches promptly
  3. Monitor logs:

    • Check access logs regularly
    • Monitor error logs
    • Set up alerts for suspicious activity

Additional Resources

Remember to regularly backup your database and media files, and keep your application and dependencies updated with security patches.

This article is part of the "Building a Project Budget Manager with Django" series. Check out Part 1, Part 2,Part 3, Part 4, Part 5,and Part 6 if you haven't already!

Getting Help

If you encounter issues during deployment:

  1. Check the PythonAnywhere error logs
  2. Visit the PythonAnywhere forums
  3. Review Django deployment documentation
  4. Join Django communities for support:

Top comments (0)