2017-01-19 04:30:21 +08:00
|
|
|
import functools
|
|
|
|
|
2011-06-16 01:29:10 +08:00
|
|
|
from django.conf import settings
|
2016-10-21 01:29:04 +08:00
|
|
|
from django.urls import LocalePrefixPattern, URLResolver, get_resolver, path
|
2014-08-12 22:54:42 +08:00
|
|
|
from django.views.i18n import set_language
|
2011-06-16 01:29:10 +08:00
|
|
|
|
2013-10-31 23:42:28 +08:00
|
|
|
|
2017-02-02 00:41:56 +08:00
|
|
|
def i18n_patterns(*urls, prefix_default_language=True):
|
2011-06-16 01:29:10 +08:00
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
Add the language code prefix to every URL pattern within this function.
|
|
|
|
This may only be used in the root URLconf, not in an included URLconf.
|
2011-06-16 01:29:10 +08:00
|
|
|
"""
|
|
|
|
if not settings.USE_I18N:
|
2016-07-24 22:00:39 +08:00
|
|
|
return list(urls)
|
2016-10-21 01:29:04 +08:00
|
|
|
return [
|
|
|
|
URLResolver(
|
|
|
|
LocalePrefixPattern(prefix_default_language=prefix_default_language),
|
|
|
|
list(urls),
|
|
|
|
)
|
|
|
|
]
|
2016-02-29 16:24:19 +08:00
|
|
|
|
|
|
|
|
2017-01-19 04:30:21 +08:00
|
|
|
@functools.lru_cache(maxsize=None)
|
2016-02-29 16:24:19 +08:00
|
|
|
def is_language_prefix_patterns_used(urlconf):
|
|
|
|
"""
|
|
|
|
Return a tuple of two booleans: (
|
2017-11-08 21:43:39 +08:00
|
|
|
`True` if i18n_patterns() (LocalePrefixPattern) is used in the URLconf,
|
2016-02-29 16:24:19 +08:00
|
|
|
`True` if the default language should be prefixed
|
|
|
|
)
|
|
|
|
"""
|
|
|
|
for url_pattern in get_resolver(urlconf).url_patterns:
|
2016-10-21 01:29:04 +08:00
|
|
|
if isinstance(url_pattern.pattern, LocalePrefixPattern):
|
|
|
|
return True, url_pattern.pattern.prefix_default_language
|
2016-02-29 16:24:19 +08:00
|
|
|
return False, False
|
2011-06-16 01:29:10 +08:00
|
|
|
|
2005-11-04 12:59:46 +08:00
|
|
|
|
2014-04-02 08:46:34 +08:00
|
|
|
urlpatterns = [
|
2016-10-21 01:29:04 +08:00
|
|
|
path('setlang/', set_language, name='set_language'),
|
2014-04-02 08:46:34 +08:00
|
|
|
]
|