Skip to main content

Quick Diagnosis

1

Check Services

Verify PostgreSQL and Redis are running
2

Review Logs

Check fkapi/api.log and fkapi/logs/performance.log
3

Test Connections

Verify database and cache connections work
4

Check Environment

Ensure .env file has all required variables

Setup Issues

Database Connection Errors

Problem: django.db.utils.OperationalError: could not connect to serverSolutions:
  1. Verify PostgreSQL is running:
# On Linux/Mac
sudo systemctl status postgresql

# On Windows
# Check Services panel

# Test with pg_isready
pg_isready
  1. Check database credentials in .env:
DATABASE_URL=postgresql://user:password@localhost:5432/fkapi
  1. Create database if missing:
createdb fkapi
  1. Test connection:
psql -U user -d fkapi -h localhost
Problem: Database not created during setupSolution:
# Create database
createdb fkapi

# Or using psql
psql -U postgres
CREATE DATABASE fkapi;
\q

# Run migrations
cd fkapi
python manage.py migrate

Redis Connection Errors

Problem: ConnectionError: Error connecting to RedisSolutions:
  1. Verify Redis is running:
# On Linux/Mac
redis-cli ping
# Should return: PONG

# On Windows
# Check Services panel or use WSL
  1. Check Redis URL in .env:
REDIS_URL=redis://localhost:6379/1
  1. Start Redis:
# On Linux/Mac
redis-server

# Using Docker
docker run -d -p 6379:6379 redis
  1. Test connection:
redis-cli
127.0.0.1:6379> PING
PONG

Module Import Errors

Problem: ModuleNotFoundError: No module named 'core'Solutions:
  1. Ensure correct directory:
cd fkapi
pwd  # Should show .../fkapi
  1. Activate virtual environment:
# Linux/Mac
source venv/bin/activate

# Windows
venv\Scripts\activate
  1. Install dependencies:
pip install -r requirements.txt
pip install -r requirements-dev.txt
  1. Verify installation:
pip list | grep django

Runtime Issues

Rate Limit Exceeded

Problem: API returns 403 with rate limit errorSolutions:
  1. Wait for rate limit to reset (default: 1 hour)
  2. Increase rate limit in .env:
API_RATE_LIMIT_RATE=200/hour
  1. Whitelist IP for testing (in .env):
RATE_LIMIT_WHITELIST=127.0.0.1,192.168.1.100
  1. Check current rate limit status:
redis-cli
KEYS "ratelimit:*"
TTL "ratelimit:127.0.0.1"
  1. Clear rate limit (development only):
redis-cli
DEL "ratelimit:127.0.0.1"

Slow API Responses

Solutions:
  1. Check Redis cache is working:
redis-cli ping
redis-cli KEYS "fkapi:*"
  1. Check response time headers:
curl -I http://localhost:8000/api/kits/arsenal-2024-home
# Look for: X-Response-Time, X-Query-Count
  1. Enable query logging (temporarily in settings.py):
LOGGING = {
    'loggers': {
        'django.db.backends': {
            'level': 'DEBUG',
        },
    },
}
  1. Review slow query logs:
tail -f fkapi/logs/performance.log
  1. Warm cache:
python manage.py warm_cache

Cache Not Working

Solutions:
  1. Verify Redis connection (see Redis section above)
  2. Check cache configuration in settings.py:
CACHES = {
    "default": {
        "BACKEND": "django.core.cache.backends.redis.RedisCache",
        "LOCATION": os.getenv("REDIS_URL"),
    }
}
  1. Clear cache manually:
redis-cli FLUSHDB
  1. Check cache keys:
redis-cli KEYS "fkapi:*"
  1. Test cache from Django shell:
python manage.py shell
>>> from django.core.cache import cache
>>> cache.set('test', 'value', 60)
>>> cache.get('test')
'value'

Database Migration Errors

Problem: django.db.migrations.exceptions.InconsistentMigrationHistorySolutions:
  1. Check migration history:
python manage.py showmigrations
  1. Fake migration (use with caution):
python manage.py migrate --fake core 0001
  1. Reset migrations (development only):
# Delete migration files (keep __init__.py)
# Recreate migrations
python manage.py makemigrations
python manage.py migrate
Solutions:
  1. Create migrations:
python manage.py makemigrations
  1. Apply migrations:
python manage.py migrate
  1. Check for conflicts:
python manage.py makemigrations --check

Testing Issues

Tests Failing

Solutions:
  1. Check pytest.ini configuration:
[pytest]
DJANGO_SETTINGS_MODULE = test_settings
pythonpath = fkapi
  1. Run tests from project root:
pytest fkapi/core/tests/
  1. Clear test database:
rm fkapi/test_db.sqlite3
  1. Verify test settings:
cat fkapi/test_settings.py

Coverage Not Working

Solutions:
  1. Install coverage tools:
pip install pytest-cov coverage
  1. Run with coverage:
pytest --cov=fkapi/core --cov-report=html
  1. Check configuration in pyproject.toml:
[tool.coverage.run]
source = ["fkapi/core"]

Scraping Issues

Scraping Fails with Connection Errors

Problem: requests.exceptions.ConnectionError or timeoutSolutions:
  1. Check internet connection
  2. Verify target website is accessible:
curl -I https://www.footballkitarchive.com
  1. Check proxy settings in core/http.py
  2. Increase timeout in .env:
HTTP_TIMEOUT=30

HTML Parsing Errors

Solutions:
  1. Check if website structure changed
  2. Log raw HTML for debugging:
logger.debug(f"HTML content: {html[:1000]}")
  1. Review HTML fixtures in tests
  2. Add defensive checks in parsers:
name = soup.find('h1')
if name:
    kit_name = name.text.strip()

Duplicate Data Issues

Solutions:
  1. Check slug uniqueness constraints
  2. Use get_or_create() instead of create():
club, created = Club.objects.get_or_create(
    slug=slug,
    defaults={'name': name}
)
  1. Find duplicates:
python manage.py shell
>>> from django.db.models import Count
>>> from core.models import Club
>>> Club.objects.values('slug').annotate(count=Count('id')).filter(count__gt=1)

API Issues

500 Internal Server Error

Solutions:
  1. Check Django logs:
tail -f fkapi/api.log
  1. Enable DEBUG mode (temporarily in .env):
DJANGO_DEBUG=True
  1. Check database connection
  2. Verify environment variables:
cat .env | grep -v "#"
  1. Test endpoint directly:
curl -v http://localhost:8000/api/health

API Documentation Not Loading

Solutions:
  1. Verify Django Ninja is installed:
pip list | grep django-ninja
  1. Check URL configuration in fkapi/urls.py:
path('api/', api.urls),
  1. Access correct URL:
http://localhost:8000/api/docs

Performance Issues

High Database Query Count

Solutions:
  1. Use select_related() for foreign keys:
Kit.objects.select_related('team', 'season')
  1. Use prefetch_related() for many-to-many:
Club.objects.prefetch_related('competitions')
  1. Check query count in response headers:
curl -I http://localhost:8000/api/kits/
# Look for: X-Query-Count
  1. Enable query logging (see Slow API Responses)

Memory Issues

Solutions:
  1. Use pagination for large datasets
  2. Process data in chunks:
for kit in Kit.objects.all().iterator(chunk_size=1000):
    process(kit)
  1. Clear cache periodically:
redis-cli FLUSHDB
  1. Monitor with django-debug-toolbar (development)

Getting More Help

Check Logs

Review fkapi/api.log and fkapi/logs/performance.log

Enable Debug

Set DJANGO_DEBUG=True for detailed error messages

Documentation

Review other docs in /docs directory

GitHub Issues

Search existing issues or create new one

Common Error Messages

django.core.exceptions.ImproperlyConfigured

Usually means missing or incorrect settings. Check:
  • Environment variables in .env
  • Database configuration
  • Redis configuration

django.db.utils.IntegrityError

Database constraint violation. Check:
  • Unique constraints
  • Foreign key relationships
  • Required fields

ninja.errors.ValidationError

API request validation failed. Check:
  • Required parameters
  • Parameter types
  • Request body format

core.exceptions.ScrapingError

Scraping operation failed. Check:
  • Network connectivity
  • Target website availability
  • HTML structure changes

Still having issues? Open an issue on GitHub with:
  • Error message and full stack trace
  • Steps to reproduce
  • Environment details (OS, Python version, etc.)
  • Relevant logs