⚠️ CUÁNDO USAR ESTA GUÍA
Aplica estas correcciones si:
- Ya desplegaste o estás desplegando en PythonAnywhere
- Tienes errores al instalar dependencias (autobahn, txaio)
- Las migraciones fallan con errores de importación
- La página muestra "Something went wrong :(" o no carga datos
- Archivos estáticos (CSS, JS, imágenes) no se muestran
Nota: Si estás en desarrollo local, usa la Guía v3.0
🎯 CONTEXTO DEL PROBLEMA
¿Por qué estos errores?
PythonAnywhere tiene ciertas limitaciones y configuraciones específicas:
- Python 3.10: La versión por defecto tiene incompatibilidades con algunas librerías modernas
- Dependencias: Algunas versiones específicas no están disponibles o causan conflictos
- Archivos estáticos: Requiere configuración especial de whitenoise
- Configuración de entorno: Variables y módulos deben importarse correctamente
📋 DIAGNÓSTICO RÁPIDO
| Síntoma | Corrección |
|---|---|
Error al instalar autobahn==25.12.2 |
Corrección #1 |
Error al instalar txaio |
Corrección #2 |
| Error en migraciones: "No module named 'os'" | Corrección #3 |
| Página no carga: "Something went wrong" | Corrección #4 |
1ERROR AL INSTALAR AUTOBAHN
ERROR Incompatibilidad de versión
ERROR: Could not find a version that satisfies the requirement autobahn==25.12.2
ERROR: No matching distribution found for autobahn==25.12.2
Building wheel for autobahn failed
Causa: Python 3.10 en PythonAnywhere no es compatible con autobahn 25.12.2
📝 SOLUCIÓN
OPCIÓN A Modificar requirements.txt
1. Ubicar tu archivo: requirements.txt
2. Buscar la línea:
autobahn==25.12.2
3. Cambiar a:
autobahn # Sin especificar versión - instalará la compatible
4. Instalar en PythonAnywhere:
# En la consola Bash de PythonAnywhere:
pip install autobahn --no-cache-dir
💡 ¿Por qué funciona?
Al no especificar versión, pip selecciona automáticamente la última versión compatible con tu Python 3.10. Típicamente instalará autobahn 23.x.x que es estable y compatible.
OPCIÓN B Especificar versión compatible
Si la Opción A no funciona, prueba con una versión específica compatible:
autobahn==23.6.2
✅ Verificar instalación exitosa
# Verificar que se instaló correctamente:
pip show autobahn
# Deberías ver algo como:
# Name: autobahn
# Version: 23.6.2
# Summary: WebSocket client & server library, WAMP real-time framework
2ERROR AL INSTALAR TXAIO
ERROR Incompatibilidad de versión de Python
ERROR: Package 'txaio' requires a different Python: 3.10.x not in '>=3.11'
ERROR: Could not build wheels for txaio
ImportError: cannot import name 'txaio'
Causa: La versión de txaio en requirements.txt requiere Python 3.11+, pero PythonAnywhere usa 3.10
📝 SOLUCIÓN DEFINITIVA
MÉTODO 1 Modificar requirements.txt (RECOMENDADO)
1. Abrir requirements.txt
2. Buscar las líneas relacionadas con txaio:
txaio==23.1.1
# O simplemente:
txaio
3. Cambiar a:
txaio # Sin versión - pip elegirá la compatible
4. Instalar manualmente en orden correcto:
# En PythonAnywhere Bash Console:
# Primero txaio (sin versión específica):
pip install txaio --no-cache-dir
# Luego autobahn (depende de txaio):
pip install autobahn --no-cache-dir
# Finalmente el resto:
pip install -r requirements.txt
✅ ¿Por qué este orden?
autobahn depende de txaio, por lo que debe instalarse primero. Al no especificar versiones, pip resuelve las dependencias automáticamente con versiones compatibles.
MÉTODO 2 Instalar cada dependencia manualmente
Si el método 1 falla, instala una por una las dependencias principales:
# Instalar en este orden:
pip install Django==4.2
pip install djangorestframework==3.14.0
pip install mysqlclient
pip install txaio
pip install autobahn
pip install channels==4.0.0
pip install channels-redis==4.1.0
pip install django-cors-headers
pip install PyJWT
pip install django-allauth
pip install django-oauth-toolkit
MÉTODO 3 Actualizar Python a 3.11
⚠️ Opción avanzada
Si tienes una cuenta de PythonAnywhere de pago, puedes cambiar la versión de Python:
- Ve a Web → tu aplicación
- En Code, busca Python version
- Selecciona 3.11
- Recarga la aplicación
Nota: Esto no está disponible en cuentas gratuitas.
✅ Verificar instalación exitosa
# Verificar txaio:
python -c "import txaio; print(txaio.__version__)"
# Verificar autobahn:
python -c "import autobahn; print(autobahn.__version__)"
# Si no hay errores, ¡está funcionando!
3ERROR EN MIGRACIONES
ERROR ModuleNotFoundError al ejecutar migraciones
python manage.py migrate --settings=biblioteca_project.settings_production
Traceback (most recent call last):
File "manage.py", line 11, in main
from django.core.management import execute_from_command_line
File ".../settings_production.py", line 5, in
DEBUG = os.getenv('DEBUG', 'False') == 'True'
NameError: name 'os' is not defined
ModuleNotFoundError: No module named 'os'
Causa: Falta importar el módulo os en settings_production.py
📝 SOLUCIÓN
1️⃣ Ubicar el archivo
Abre biblioteca_project/settings_production.py
2️⃣ Verificar las primeras líneas
Si el archivo se ve así:
from .settings import *
DEBUG = os.getenv('DEBUG', 'False') == 'True'
ALLOWED_HOSTS = ['tuusuario.pythonanywhere.com']
3️⃣ Agregar la importación de os AL INICIO
El archivo debe quedar así:
import os # ⬅️ AGREGAR ESTA LÍNEA PRIMERO
from .settings import *
DEBUG = os.getenv('DEBUG', 'False') == 'True'
ALLOWED_HOSTS = ['tuusuario.pythonanywhere.com']
# ... resto de la configuración ...
💡 ¿Por qué sucede esto?
Python requiere que los módulos se importen antes de usarse. El error ocurre porque settings_production.py usa os.getenv() pero no tiene import os al inicio. Aunque settings.py ya lo importe, cada archivo debe tener sus propias importaciones.
4️⃣ Guardar y probar migraciones
# En PythonAnywhere Bash Console:
cd ~/tuusuario.pythonanywhere.com
python manage.py migrate --settings=biblioteca_project.settings_production
✅ Éxito esperado
Operations to perform:
Apply all migrations: admin, auth, contenttypes, libros, sessions
Running migrations:
Applying libros.0001_initial... OK
Applying libros.0002_auto_... OK
...
All migrations applied successfully!
🔍 Otros módulos comunes a verificar
Asegúrate de que settings_production.py tenga todas las importaciones necesarias:
import os
from pathlib import Path
from .settings import *
# Configuración específica de producción...
DEBUG = False
ALLOWED_HOSTS = ['tuusuario.pythonanywhere.com']
# Base de datos MySQL (ejemplo):
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': os.getenv('DB_NAME', 'tuusuario$biblioteca'),
'USER': os.getenv('DB_USER', 'tuusuario'),
'PASSWORD': os.getenv('DB_PASSWORD', 'tu_password'),
'HOST': 'tuusuario.mysql.pythonanywhere-services.com',
}
}
4PÁGINA NO CARGA DATOS
ERROR Something went wrong :(
Al acceder a tu sitio web en PythonAnywhere ves:
- Mensaje: "Something went wrong :("
- Página en blanco
- CSS/JS no se cargan (página sin estilos)
- Imágenes no se muestran
- Error 500 Internal Server Error
Causa principal: Archivos estáticos no se están sirviendo correctamente
📝 SOLUCIÓN: INSTALAR WHITENOISE
¿Qué es WhiteNoise?
WhiteNoise es una librería que permite a Django servir archivos estáticos (CSS, JavaScript, imágenes) de forma eficiente en producción sin necesidad de configurar un servidor web adicional como Nginx.
1️⃣ Instalar whitenoise
# En PythonAnywhere Bash Console:
pip install whitenoise
2️⃣ Configurar en settings.py
Abre biblioteca_project/settings.py y modifica:
A) Agregar en INSTALLED_APPS:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Third party apps
'whitenoise.runserver_nostatic', # ⬅️ AGREGAR AQUÍ (ANTES de staticfiles)
'rest_framework',
'corsheaders',
# ... resto de apps ...
]
B) Modificar MIDDLEWARE (IMPORTANTE EL ORDEN):
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware', # ⬅️ AGREGAR AQUÍ (después de SecurityMiddleware)
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
# ... resto de middleware ...
]
⚠️ ORDEN CRÍTICO
WhiteNoiseMiddleware DEBE estar:
- ✅ Después de
SecurityMiddleware - ✅ Antes de todos los demás middleware
Si no respetas este orden, WhiteNoise no funcionará.
C) Configurar STATIC_ROOT y STATICFILES_STORAGE:
# Al final de settings.py:
import os
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
# Archivos estáticos
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # ⬅️ Dónde se recopilarán
# Configuración de WhiteNoise para comprimir y cachear archivos
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
# Opcional: directorios adicionales de archivos estáticos
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
3️⃣ Recopilar archivos estáticos
# En PythonAnywhere Bash Console:
python manage.py collectstatic --settings=biblioteca_project.settings_production
# Deberías ver:
# 152 static files copied to '/home/tuusuario/tuusuario.pythonanywhere.com/staticfiles'.
4️⃣ Configurar en PythonAnywhere Web
1. Ve a la pestaña Web
2. En la sección Static files, agrega:
| URL | Directory |
|---|---|
/static/ |
/home/tuusuario/tuusuario.pythonanywhere.com/staticfiles |
/media/ |
/home/tuusuario/tuusuario.pythonanywhere.com/media |
5️⃣ Recargar la aplicación
En la pestaña Web, haz clic en el botón verde grande: "Reload tuusuario.pythonanywhere.com"
✅ Verificar que funciona
- Abre tu sitio:
https://tuusuario.pythonanywhere.com - Verifica que los estilos CSS se apliquen correctamente
- Abre DevTools (F12) → Network
- Recarga la página
- Busca archivos .css y .js - deben tener código 200 OK
🔍 Solución de problemas adicionales
Si aún no funciona:
- Revisa los logs de error:
Pestaña Web → Log files → Error log
/var/log/tuusuario.pythonanywhere.com.error.log - Verifica DEBUG en producción:
Ensettings_production.py:
DEBUG = False # Debe estar en False - Verifica ALLOWED_HOSTS:
ALLOWED_HOSTS = ['tuusuario.pythonanywhere.com'] - Limpia la caché del navegador:
Ctrl + Shift + R (Windows/Linux)
Cmd + Shift + R (Mac)
✅ CHECKLIST DE DESPLIEGUE COMPLETO
Antes de dar por terminado el despliegue, verifica:
📦 1. Dependencias instaladas correctamente
| Paquete | Instalado | Verificar |
|---|---|---|
| Django | ☐ | python -c "import django; print(django.VERSION)" |
| mysqlclient | ☐ | python -c "import MySQLdb" |
| txaio | ☐ | python -c "import txaio" |
| autobahn | ☐ | python -c "import autobahn" |
| whitenoise | ☐ | python -c "import whitenoise" |
⚙️ 2. Configuración
- ☐
settings_production.pytieneimport osal inicio - ☐
DEBUG = Falseen producción - ☐
ALLOWED_HOSTSincluye tu dominio de PythonAnywhere - ☐ WhiteNoise configurado en MIDDLEWARE
- ☐
STATIC_ROOTconfigurado correctamente - ☐ Base de datos MySQL configurada y conectada
🗄️ 3. Base de datos
- ☐ Base de datos creada en PythonAnywhere
- ☐ Credenciales correctas en
settings_production.py - ☐ Migraciones ejecutadas sin errores:
python manage.py migrate --settings=biblioteca_project.settings_production - ☐ Superusuario creado:
python manage.py createsuperuser --settings=biblioteca_project.settings_production
📁 4. Archivos estáticos
- ☐
collectstaticejecutado correctamente - ☐ Directorio
/static/configurado en Web tab - ☐ CSS y JavaScript se cargan en el navegador
🌐 5. Configuración Web de PythonAnywhere
- ☐ WSGI file apunta a
settings_production - ☐ Virtualenv configurado correctamente
- ☐ Static files mapeados
- ☐ Aplicación recargada después de cada cambio
🧪 6. Pruebas funcionales
- ☐ Página principal carga sin errores
- ☐ Panel de administración funciona:
/admin/ - ☐ API responde correctamente:
/api/libros/ - ☐ Login y autenticación funcionan
- ☐ No hay errores en error.log
🔧 SOLUCIÓN DE PROBLEMAS ADICIONALES
❌ Error: "No module named 'MySQLdb'"
Solución:
pip install mysqlclient
❌ Error: "Access denied for user"
Solución: Verifica las credenciales de la base de datos en settings_production.py
- Nombre de BD:
tuusuario$nombre_bd - Usuario:
tuusuario - Host:
tuusuario.mysql.pythonanywhere-services.com
❌ Error: "ImproperlyConfigured: WSGI application 'application' could not be loaded"
Solución: Verifica tu archivo WSGI. Debe incluir:
import os
import sys
# Add your project directory to the sys.path
path = '/home/tuusuario/tuusuario.pythonanywhere.com'
if path not in sys.path:
sys.path.append(path)
# Set environment variables
os.environ['DJANGO_SETTINGS_MODULE'] = 'biblioteca_project.settings_production'
# Import Django application
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
❌ Error: "Static files not found (404)"
Solución en orden:
- Ejecuta:
python manage.py collectstatic - Verifica que el directorio
staticfiles/existe - Configura Static files en Web tab
- Recarga la aplicación
- Limpia caché del navegador
📚 RECURSOS Y CONTACTO
🔗 Enlaces útiles
- PythonAnywhere Help: help.pythonanywhere.com
- WhiteNoise Docs: whitenoise.evans.io
- Django Deployment Checklist: docs.djangoproject.com
💡 Consejos finales
- Siempre revisa los logs de error cuando algo no funcione
- Guarda copias de seguridad de tu base de datos antes de cambios importantes
- Documenta todas las configuraciones específicas de tu proyecto
- Prueba cada funcionalidad después del despliegue
- Mantén actualizadas tus dependencias de seguridad
📧 ¿Necesitas más ayuda?
Si después de aplicar todas estas correcciones aún tienes problemas:
- Consulta con tus compañeros: No dejes de buscar la solución
- Revisa la documentación oficial de PythonAnywhere
- Comparte los logs de error para diagnóstico específico