0

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()
Community
  • 1
  • 1
shaun shia
  • 1,042
  • 2
  • 9
  • 14

1 Answers1

2

Usually caused by using a mix of imports where some imports are via the site package and some don't. You can add:

sys.path.insert(0,"/home/my/myweb/mywebsite")

and that may help.

For a bit of a discussion of the problem see:

Graham Dumpleton
  • 57,726
  • 6
  • 119
  • 134