You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

i18n.py 1.2KB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839
  1. import functools
  2. from django.conf import settings
  3. from django.urls import LocalePrefixPattern, URLResolver, get_resolver, path
  4. from django.views.i18n import set_language
  5. def i18n_patterns(*urls, prefix_default_language=True):
  6. """
  7. Add the language code prefix to every URL pattern within this function.
  8. This may only be used in the root URLconf, not in an included URLconf.
  9. """
  10. if not settings.USE_I18N:
  11. return list(urls)
  12. return [
  13. URLResolver(
  14. LocalePrefixPattern(prefix_default_language=prefix_default_language),
  15. list(urls),
  16. )
  17. ]
  18. @functools.lru_cache(maxsize=None)
  19. def is_language_prefix_patterns_used(urlconf):
  20. """
  21. Return a tuple of two booleans: (
  22. `True` if i18n_patterns() (LocalePrefixPattern) is used in the URLconf,
  23. `True` if the default language should be prefixed
  24. )
  25. """
  26. for url_pattern in get_resolver(urlconf).url_patterns:
  27. if isinstance(url_pattern.pattern, LocalePrefixPattern):
  28. return True, url_pattern.pattern.prefix_default_language
  29. return False, False
  30. urlpatterns = [
  31. path('setlang/', set_language, name='set_language'),
  32. ]