Initial commit

This commit is contained in:
Zhongwei Li
2025-11-30 08:46:40 +08:00
commit 66f1bf4fb0
33 changed files with 6059 additions and 0 deletions

View File

@@ -0,0 +1,480 @@
# Troubleshooting: Django Errors
[← Back to main skill](../SKILL.md)
---
## Issue: `django-admin: command not found` {#django-admin}
**After installing Django, command doesn't work**
### Solutions:
**Ensure venv is activated:**
```bash
source venv/bin/activate # macOS/Linux
venv\Scripts\activate # Windows
```
**Use `python -m django` instead:**
```bash
python -m django --version
python -m django startproject myproject
```
**Check Django is installed:**
```bash
pip list | grep Django
# or
pip show Django
```
**Reinstall Django:**
```bash
pip install --force-reinstall Django
```
---
## Issue: Port 8000 Already in Use {#port-in-use}
**Error:**
```
Error: That port is already in use.
```
### Solutions:
**Use different port:**
```bash
python manage.py runserver 8001
python manage.py runserver 0.0.0.0:8080
```
**Kill process using port 8000:**
**macOS/Linux:**
```bash
lsof -ti:8000 | xargs kill -9
```
**Windows (PowerShell):**
```powershell
netstat -ano | findstr :8000
# Note the PID, then:
taskkill /PID <pid> /F
```
**Windows (Command Prompt):**
```cmd
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:**
```bash
which python # Should point to venv/bin/python
echo $VIRTUAL_ENV # Should show venv path
```
**Check Django installation:**
```bash
pip list
pip show Django
```
**Install Django in venv:**
```bash
source venv/bin/activate
pip install Django
```
**Check you're using venv Python:**
```bash
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:**
```python
# 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:**
```bash
python manage.py migrate
```
**Check migration files exist:**
```bash
ls */migrations/
# Should see 0001_initial.py files
```
**Reset database (development only!):**
```bash
rm db.sqlite3
python manage.py migrate
```
**Make migrations if they don't exist:**
```bash
python manage.py makemigrations
python manage.py migrate
```
---
## Issue: Static Files Not Loading
**CSS/JS files show 404 in browser**
### Solutions:
**Run collectstatic:**
```bash
python manage.py collectstatic
```
**Check STATIC_URL in settings.py:**
```python
STATIC_URL = '/static/'
```
**For development, ensure DEBUG=True:**
```python
DEBUG = True
```
**Check INSTALLED_APPS includes:**
```python
INSTALLED_APPS = [
...
'django.contrib.staticfiles',
]
```
---
## Issue: Template Not Found
**Error:**
```
TemplateDoesNotExist at /path/
```
### Solutions:
**Check template path:**
```python
# settings.py
TEMPLATES = [
{
'DIRS': [BASE_DIR / 'templates'], # Add this
...
},
]
```
**Create templates directory:**
```bash
mkdir -p templates
```
**Check template name matches:**
```python
# 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:**
```python
# settings.py
DEBUG = False # In production
ALLOWED_HOSTS = ['yourdomain.com', 'www.yourdomain.com']
```
**For development:**
```python
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:**
```python
# settings.py
MIDDLEWARE = [
...
'django.middleware.csrf.CsrfViewMiddleware',
...
]
```
**Include CSRF token in forms:**
```html
<form method="post">
{% csrf_token %}
...
</form>
```
**For AJAX, include CSRF token in headers:**
```javascript
// 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:**
```bash
python manage.py migrate
```
**Create superuser:**
```bash
python manage.py createsuperuser
```
**Check URL configuration:**
```python
# urls.py
from django.contrib import admin
urlpatterns = [
path('admin/', admin.site.urls),
]
```
**Ensure admin app is installed:**
```python
# 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:**
```python
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'new_name.settings')
```
**asgi.py:**
```python
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'new_name.settings')
```
**wsgi.py:**
```python
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:**
```python
# ❌ Bad - circular import
# models.py
from .views import something
# views.py
from .models import Model
```
**Use lazy imports:**
```python
# ✅ Good - import inside function
def my_view(request):
from .models import Model # Import here
...
```
**Or use Django's get_model:**
```python
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:**
```bash
python --version # Should be 3.8+
```
**Look for common syntax errors:**
```python
# ❌ 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:**
```bash
python -m py_compile backend/settings.py
```
---
## Quick Diagnostic Commands
**Check Django installation:**
```bash
python -m django --version
```
**Check Python version:**
```bash
python --version
```
**Run system checks:**
```bash
python manage.py check
python manage.py check --deploy
```
**List installed packages:**
```bash
pip list
```
**Check migrations status:**
```bash
python manage.py showmigrations
```
**Test database connection:**
```bash
python manage.py dbshell
```
---
[← Back to django-project-setup](../SKILL.md)