Django and SaaS. How to use separate database for each Django site?

依然范特西╮ 提交于 2019-12-03 09:04:47

You should create a "clients" folder, and a subdirectory per client. In each subdirectory, create a site_settings.py file as such:

import os.path

# import global settings
from settings import *

# this is barely just the name of the client dir, you might want to use that
SITE_NAME = __file__.split('/')[-2]
# this is the directory of the client website
CLIENT_ROOT = os.path.abspath(os.path.dirname(__file__))

DATABASES = {
    'default': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        'NAME': SITE_NAME,
        'USER': SITE_NAME,
        'PASSWORD': 'some random password',
    }  
}

# you might want this too so that each client have his own MEDIA_ROOT
MEDIA_ROOT = os.path.join(CLIENT_ROOT, 'upload')

Then don't forget to use the --settings switch for management commands. For example:

./manage.py syncdb --settings=clients.demo.site_settings

Don't forget that each client will require to have his own extra stuff. For example, if you use haystack with whoosh, you need to add this so that it doesn't get mixed up between clients:

HAYSTACK_WHOOSH_PATH = os.path.join(CLIENT_ROOT, 'whoosh')

Or with django-zstask:

ZTASKD_URL = 'ipc:///tmp/%s_ztask.sock' % SITE_NAME

Or with JohnnyCache:

JOHNNY_MIDDLEWARE_KEY_PREFIX=SITE_NAME
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!