Django MySQL Connection Troubleshooting: Resolving OperationalError (2002)

This error message indicates that your Django application is unable to establish a connection to your MySQL server, specifically targeting the host named 'db'. To resolve this issue, follow these systematic troubleshooting steps:

  1. Verify MySQL service status On Linux systems, use:

    sudo systemctl status mysql
    
    

    On Windows, check the service status through the Services console or run:

    netstat -an | findstr 3306
    
    

    If the service isn't running, start it using:

    sudo systemctl start mysql
    
    
  2. Review database configuration in your Django settings Ensure your settings.py contains proper MySQL connection parameters:

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'ecommerce_db',
            'USER': 'app_user',
            'PASSWORD': 'secure_password',
            'HOST': 'db',
            'PORT': '3306',
            'OPTIONS': {
                'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
            }
        }
    }
    
    
  3. Test network connectivity Use the ping command to verify connectivity between your Django application server and MySQL host:

    ping db-server
    
    

    If the ping fails, investigtae network configurations and firewall settings that might be blocking the connection.

  4. Validate database credentials Connect directly to MySQL using the credentials specified in your Django settings:

    mysql -u app_user -p -h db-server
    
    

    Enter the password when prompted. If authentication fails, verify the user exists and has proper privileges.

  5. Restart services After making configuration changes, restart both MySQL and your Django application:

    sudo systemctl restart mysql
    sudo systemctl restart gunicorn  # or your preferred WSGI server
    
    

Sample Django project structure:

/ecommerce_platform
├── manage.py
├── core/
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── products/
│   ├── __init__.py
│   ├── models.py
│   ├── views.py
│   └── migrations/
└── customers/
    ├── __init__.py
    ├── models.py
    └── views.py

Example model implementation:

# products/models.py
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)
    stock_quantity = models.PositiveIntegerField()
    created_at = models.DateTimeField(auto_now_add=True)
    
    def __str__(self):
        return self.name

Test case implementation:

# products/tests.py
from django.test import TestCase
from django.urls import reverse
from .models import Product

class ProductModelTest(TestCase):
    def setUp(self):
        self.product = Product.objects.create(
            name="Smartphone",
            description="Latest model with advanced features",
            price=599.99,
            stock_quantity=100
        )
    
    def test_product_creation(self):
        self.assertEqual(self.product.name, "Smartphone")
        self.assertEqual(self.product.price, 599.99)
    
    def test_product_list_view(self):
        response = self.client.get(reverse('product-list'))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "Smartphone")

Database migration command:

python manage.py makemigrations products
python manage.py migrate

For applications requiring AI integrasion, you might implement a recommendation system that analyzes user behavior. First, create a model to track user interactions:

# customers/models.py
from django.db import models
from django.contrib.auth.models import User

class UserActivity(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    product = models.ForeignKey('products.Product', on_delete=models.CASCADE)
    action = models.CharField(max_length=50)  # 'view', 'purchase', 'like'
    timestamp = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        indexes = [
            models.Index(fields=['user', 'timestamp']),
            models.Index(fields=['product']),
        ]

To analyze this data with machine learning, you could export it to a format compatible with libraries like scikit-learn or pandas:

# analytics/data_processor.py
import pandas as pd
from customers.models import UserActivity
from products.models import Product

def prepare_user_data(user_id):
    activities = UserActivity.objects.filter(user_id=user_id)
    df = pd.DataFrame.from_records(
        activities.values('action', 'product__name', 'timestamp'),
        index='timestamp'
    )
    return df

Tags: Django MySQL database connection Python ORM web development

Posted on Sun, 13 Sep 2026 16:01:29 +0000 by bseven