1 # -*- coding: utf-8 -*-
2 # This file is part of PrawoKultury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 from collections import namedtuple
8 from django.conf import settings
9 from django.conf.urls import patterns
10 from django.core.urlresolvers import LocaleRegexURLResolver
11 from django.utils.translation import get_language, string_concat
14 class EntryType(namedtuple('EntryType', 'db slug commentable on_main')):
15 def __unicode__(self):
16 return unicode(self.slug)
19 def field_getter(name):
22 val = getattr(self, "%s_%s" % (name, get_language()))
24 val = getattr(self, "%s_%s" % (name, settings.LANGUAGE_CODE))
29 def add_translatable(model, fields, languages=None):
30 """Adds some translatable fields to a model, and a getter."""
32 languages = settings.LANGUAGES
33 for name, field in fields.items():
34 for lang_code, lang_name in languages:
35 new_field = copy(field)
36 if field.verbose_name:
37 new_field.verbose_name = string_concat(field.verbose_name, ' [%s]' % lang_code)
38 new_field.contribute_to_class(model, "%s_%s" % (name, lang_code))
39 setattr(model, name, field_getter(name))
43 class MyLocaleRegexURLResolver(LocaleRegexURLResolver):
45 A URL resolver that always matches the active language code as URL prefix.
47 Rather than taking a regex argument, we just override the ``regex``
48 function to always return the active language-code as regex.
52 language_code = get_language()
53 if language_code == settings.LANGUAGE_CODE:
55 if language_code not in self._regex_dict:
56 regex_compiled = re.compile('^%s/' % language_code, re.UNICODE)
57 self._regex_dict[language_code] = regex_compiled
58 return self._regex_dict[language_code]
61 def i18n_patterns(prefix, *args):
63 Adds the language code prefix to every URL pattern within this
64 function. This may only be used in the root URLconf, not in an included
68 pattern_list = patterns(prefix, *args)
69 if not settings.USE_I18N:
71 return pattern_list + [MyLocaleRegexURLResolver(pattern_list)]