Python 3, Django 1.7+ compatilibity, some tests.
[fnpdjango.git] / fnpdjango / utils / urls.py
1 """
2 Utilities for urlconfs.
3 """
4
5 import re
6 from django.conf import settings
7 from django.conf.urls import patterns
8 from django.core.urlresolvers import LocaleRegexURLResolver
9 from django.utils.translation import get_language, string_concat
10
11
12 class MyLocaleRegexURLResolver(LocaleRegexURLResolver):
13     """
14     A URL resolver that always matches the active language code as URL prefix.
15
16     Rather than taking a regex argument, we just override the ``regex``
17     function to always return the active language-code as regex.
18     """
19     @property
20     def regex(self):
21         language_code = get_language()
22         if language_code == settings.LANGUAGE_CODE:
23             return re.compile('')
24         if language_code not in self._regex_dict:
25             regex_compiled = re.compile('^%s/' % language_code, re.UNICODE)
26             self._regex_dict[language_code] = regex_compiled
27         return self._regex_dict[language_code]
28
29
30 def i18n_patterns(prefix, *args):
31     """
32     Adds the language code prefix to every URL pattern within this
33     function. This may only be used in the root URLconf, not in an included
34     URLconf.
35
36     """
37     pattern_list = patterns(prefix, *args)
38     if not settings.USE_I18N:
39         return pattern_list
40     return pattern_list + [MyLocaleRegexURLResolver(pattern_list)]