When testing my django website by python manage.py runserver 0.0.0.0:8000
, there is no error.
But if I deploy it to production with apache and mod_wsgi, it reports error cannot import name connection
.
I find some other questions like django 1.4 database router - "cannot import name connection" suggesting adding from django.db import connections
into settings.py.
But I found adding this import can prevent this error, but it also disables database router.
I think it may due to different running environment between manage.py runserver
and WSGI.
This is how my wsgi.py looks like
import os
import sys
sys.path.insert(0,"/home/my/myweb")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mywebsite.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
How can I fix this bug?
My python version is 2.7 and django version is 1.4.3
Edit 1:
My OS is CentOS 6.4, on this server:
If I run it using python manage.py runserver 0.0.0.0:8000
, no error.
If I remove database router, it can work under WSGI.
But database router and WSGI cannot work together.
Any advice is appreciated.
Edit 2:
Thanks to @Graham Dumpleton, I figured it out by myself.
This is the wsgy.py that works for me.
import sys
sys.path.insert(0, '/home/my/myweb')
from mywebsite import settings
import django.core.management
django.core.management.setup_environ(settings)
utility = django.core.management.ManagementUtility()
command = utility.fetch_command('runserver')
command.validate()
import django.conf
import django.utils
django.utils.translation.activate(django.conf.settings.LANGUAGE_CODE)
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()