我设法弄清楚了这一点。首先,您需要阅读文档:https ://docs.djangoproject.com/en/dev/topics/i18n/translation/
@1 - 我基于http://djangosnippets.org/snippets/2037/编写了自己的中间件(将这个中间件作为MIDDLEWARE_CLASSES
列表中的第一个至关重要)
import threading
from django.http import Http404
from django.conf import settings
request_cfg = threading.local()
class RouterMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
lang = request.LANGUAGE_CODE
if lang in settings.LANGUAGES:
request_cfg.lang = lang
else:
raise Http404()
def process_response(self, request, response):
if hasattr(request_cfg, 'lang'):
del request_cfg.lang
return response
class DatabaseRouter(object):
def _default_db(self):
if hasattr(request_cfg, 'lang') and request_cfg.lang in settings.DATABASES:
return request_cfg.lang
else:
return 'default'
def db_for_read(self, model, **hints):
return self._default_db()
def db_for_write(self, model, **hints):
return self._default_db()
@2 - 可以使用request.LANGUAGE_CODE
@3 - 在文档中有解释:https ://docs.djangoproject.com/en/dev/topics/i18n/translation/#internationalization-in-url-patterns