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')):
16 def __unicode__(self):
17 return unicode(self.slug)
20 def field_getter(name):
23 val = getattr(self, "%s_%s" % (name, get_language()))
25 val = getattr(self, "%s_%s" % (name, settings.LANGUAGE_CODE))
30 def add_translatable(model, fields, languages=None):
31 """Adds some translatable fields to a model, and a getter."""
33 languages = settings.LANGUAGES
34 for name, field in fields.items():
35 for lang_code, lang_name in languages:
36 new_field = copy(field)
37 if field.verbose_name:
38 new_field.verbose_name = string_concat(field.verbose_name, ' [%s]' % lang_code)
39 new_field.contribute_to_class(model, "%s_%s" % (name, lang_code))
40 setattr(model, name, field_getter(name))
44 class MyLocaleRegexURLResolver(LocaleRegexURLResolver):
46 A URL resolver that always matches the active language code as URL prefix.
48 Rather than taking a regex argument, we just override the ``regex``
49 function to always return the active language-code as regex.
53 language_code = get_language()
54 if language_code == settings.LANGUAGE_CODE:
56 if language_code not in self._regex_dict:
57 regex_compiled = re.compile('^%s/' % language_code, re.UNICODE)
58 self._regex_dict[language_code] = regex_compiled
59 return self._regex_dict[language_code]
62 def i18n_patterns(prefix, *args):
64 Adds the language code prefix to every URL pattern within this
65 function. This may only be used in the root URLconf, not in an included
69 pattern_list = patterns(prefix, *args)
70 if not settings.USE_I18N:
72 return pattern_list + [MyLocaleRegexURLResolver(pattern_list)]