Files
gh-otoshek-claude-code-toolkit/skills/django-setup/troubleshooting/django-errors.md
2025-11-30 08:46:40 +08:00

7.3 KiB

Troubleshooting: Django Errors

← Back to main skill


Issue: django-admin: command not found

After installing Django, command doesn't work

Solutions:

Ensure venv is activated:

source venv/bin/activate  # macOS/Linux
venv\Scripts\activate     # Windows

Use python -m django instead:

python -m django --version
python -m django startproject myproject

Check Django is installed:

pip list | grep Django
# or
pip show Django

Reinstall Django:

pip install --force-reinstall Django

Issue: Port 8000 Already in Use

Error:

Error: That port is already in use.

Solutions:

Use different port:

python manage.py runserver 8001
python manage.py runserver 0.0.0.0:8080

Kill process using port 8000:

macOS/Linux:

lsof -ti:8000 | xargs kill -9

Windows (PowerShell):

netstat -ano | findstr :8000
# Note the PID, then:
taskkill /PID <pid> /F

Windows (Command Prompt):

FOR /F "tokens=5" %P IN ('netstat -ano ^| findstr :8000') DO TaskKill /PID %P /F

Issue: ModuleNotFoundError: No module named 'django'

Django installed but Python can't find it

Solutions:

Verify venv is activated:

which python  # Should point to venv/bin/python
echo $VIRTUAL_ENV  # Should show venv path

Check Django installation:

pip list
pip show Django

Install Django in venv:

source venv/bin/activate
pip install Django

Check you're using venv Python:

python --version
which python

Issue: django.core.exceptions.ImproperlyConfigured

Common misconfigurations

SECRET_KEY not set

Error:

ImproperlyConfigured: The SECRET_KEY setting must not be empty.

Solution:

  • Don't delete SECRET_KEY from settings.py
  • If using environment variables, ensure .env file exists

Database configuration error

Error:

ImproperlyConfigured: settings.DATABASES is improperly configured

Solution - Check database settings:

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

Issue: Migrations Not Applying

Error:

django.db.utils.OperationalError: no such table

Solutions:

Run migrations:

python manage.py migrate

Check migration files exist:

ls */migrations/
# Should see 0001_initial.py files

Reset database (development only!):

rm db.sqlite3
python manage.py migrate

Make migrations if they don't exist:

python manage.py makemigrations
python manage.py migrate

Issue: Static Files Not Loading

CSS/JS files show 404 in browser

Solutions:

Run collectstatic:

python manage.py collectstatic

Check STATIC_URL in settings.py:

STATIC_URL = '/static/'

For development, ensure DEBUG=True:

DEBUG = True

Check INSTALLED_APPS includes:

INSTALLED_APPS = [
    ...
    'django.contrib.staticfiles',
]

Issue: Template Not Found

Error:

TemplateDoesNotExist at /path/

Solutions:

Check template path:

# settings.py
TEMPLATES = [
    {
        'DIRS': [BASE_DIR / 'templates'],  # Add this
        ...
    },
]

Create templates directory:

mkdir -p templates

Check template name matches:

# views.py
return render(request, 'index.html')  # Must match file name exactly

Issue: ALLOWED_HOSTS Error in Production

Error:

Invalid HTTP_HOST header: 'yourdomain.com'. You may need to add 'yourdomain.com' to ALLOWED_HOSTS.

Solution:

Add domain to ALLOWED_HOSTS:

# settings.py
DEBUG = False  # In production
ALLOWED_HOSTS = ['yourdomain.com', 'www.yourdomain.com']

For development:

DEBUG = True
ALLOWED_HOSTS = []  # Empty list allows localhost automatically

Issue: CSRF Verification Failed

Error:

Forbidden (403)
CSRF verification failed. Request aborted.

Solutions:

Ensure CSRF middleware is enabled:

# settings.py
MIDDLEWARE = [
    ...
    'django.middleware.csrf.CsrfViewMiddleware',
    ...
]

Include CSRF token in forms:

<form method="post">
    {% csrf_token %}
    ...
</form>

For AJAX, include CSRF token in headers:

// Get CSRF token from cookie
const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;

fetch('/api/endpoint/', {
    method: 'POST',
    headers: {
        'X-CSRFToken': csrftoken
    }
})

Issue: Admin Interface Not Working

Can't access /admin/

Solutions:

Run migrations:

python manage.py migrate

Create superuser:

python manage.py createsuperuser

Check URL configuration:

# urls.py
from django.contrib import admin

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

Ensure admin app is installed:

# settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
]

Issue: Project Won't Start After Renaming

Renamed project but errors occur

Solution:

Update references in these files:

manage.py:

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'new_name.settings')

asgi.py:

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'new_name.settings')

wsgi.py:

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'new_name.settings')

Rename project directory itself


Issue: Circular Import Errors

Error:

ImportError: cannot import name 'X' from partially initialized module 'Y'

Solutions:

Avoid circular imports:

# ❌ Bad - circular import
# models.py
from .views import something

# views.py
from .models import Model

Use lazy imports:

# ✅ Good - import inside function
def my_view(request):
    from .models import Model  # Import here
    ...

Or use Django's get_model:

from django.apps import apps
Model = apps.get_model('app_name', 'ModelName')

Issue: SyntaxError in settings.py

Error:

SyntaxError: invalid syntax

Solutions:

Check Python version:

python --version  # Should be 3.8+

Look for common syntax errors:

# ❌ Missing comma
INSTALLED_APPS = [
    'django.contrib.admin'  # Missing comma!
    'django.contrib.auth',
]

# ✅ Correct
INSTALLED_APPS = [
    'django.contrib.admin',  # Comma here
    'django.contrib.auth',
]

Validate Python syntax:

python -m py_compile backend/settings.py

Quick Diagnostic Commands

Check Django installation:

python -m django --version

Check Python version:

python --version

Run system checks:

python manage.py check
python manage.py check --deploy

List installed packages:

pip list

Check migrations status:

python manage.py showmigrations

Test database connection:

python manage.py dbshell

← Back to django-project-setup