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 hasattr(field, 'verbose_name') and field.verbose_name:
38 new_field.verbose_name = string_concat(field.verbose_name, ' [%s]' % lang_code)
40 new_field.contribute_to_class(model, "%s_%s" % (name, lang_code))
41 setattr(model, name, field_getter(name))
45 class MyLocaleRegexURLResolver(LocaleRegexURLResolver):
47 A URL resolver that always matches the active language code as URL prefix.
49 Rather than taking a regex argument, we just override the ``regex``
50 function to always return the active language-code as regex.
54 language_code = get_language()
55 if language_code == settings.LANGUAGE_CODE:
57 if language_code not in self._regex_dict:
58 regex_compiled = re.compile('^%s/' % language_code, re.UNICODE)
59 self._regex_dict[language_code] = regex_compiled
60 return self._regex_dict[language_code]
63 def i18n_patterns(prefix, *args):
65 Adds the language code prefix to every URL pattern within this
66 function. This may only be used in the root URLconf, not in an included
70 pattern_list = patterns(prefix, *args)
71 if not settings.USE_I18N:
73 return pattern_list + [MyLocaleRegexURLResolver(pattern_list)]