Skip to content

Commit

Permalink
i18n
Browse files Browse the repository at this point in the history
  • Loading branch information
winniehell authored and coordt committed Mar 20, 2013
1 parent 591680a commit 89c7333
Show file tree
Hide file tree
Showing 8 changed files with 63 additions and 43 deletions.
3 changes: 3 additions & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,7 @@ recursive-include doc_src *.rst *.txt *.png *.css *.html *.js
include doc_src/Makefile
include doc_src/make.bat

recursive-include categories/locale *.mo *.po
recursive-include categories/editor/locale *.mo *.po

prune example
5 changes: 3 additions & 2 deletions categories/admin.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from django.contrib import admin
from django import forms
from django.utils.translation import ugettext_lazy as _

from .genericcollection import GenericCollectionTabularInline
from .settings import RELATION_MODELS, JAVASCRIPT_URL, REGISTER_ADMIN
Expand Down Expand Up @@ -46,12 +47,12 @@ class CategoryAdmin(CategoryBaseAdmin):
(None, {
'fields': ('parent', 'name', 'thumbnail', 'active')
}),
('Meta Data', {
(_('Meta Data'), {
'fields': ('alternate_title', 'alternate_url', 'description',
'meta_keywords', 'meta_extra'),
'classes': ('collapse',),
}),
('Advanced', {
(_('Advanced'), {
'fields': ('order', 'slug'),
'classes': ('collapse',),
}),
Expand Down
27 changes: 14 additions & 13 deletions categories/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from django import forms
from django.template.defaultfilters import slugify
from django.utils.encoding import force_unicode
from django.utils.translation import ugettext as _

from mptt.models import MPTTModel
from mptt.fields import TreeForeignKey
Expand Down Expand Up @@ -36,11 +37,11 @@ class CategoryBase(MPTTModel):
parent = TreeForeignKey('self',
blank=True,
null=True,
related_name="children",
verbose_name='Parent')
name = models.CharField(max_length=100)
slug = models.SlugField()
active = models.BooleanField(default=True)
related_name='children',
verbose_name=_('parent'))
name = models.CharField(max_length=100, verbose_name=_('name'))
slug = models.SlugField(verbose_name=_('slug'))
active = models.BooleanField(default=True, verbose_name=_('active'))

objects = CategoryManager()
tree = TreeManager()
Expand Down Expand Up @@ -100,8 +101,8 @@ def clean(self):
**kwargs).values('id', 'slug'
) if c['id'] != self.instance.id]
if self.cleaned_data['slug'] in this_level_slugs:
raise forms.ValidationError("The slug must be unique among "
"the items at its level.")
raise forms.ValidationError(_('The slug must be unique among '
'the items at its level.'))

# Validate Category Parent
# Make sure the category doesn't set itself or any of its children as
Expand All @@ -110,11 +111,11 @@ def clean(self):
if self.cleaned_data.get('parent', None) is None or self.instance.id is None:
return self.cleaned_data
elif self.cleaned_data['parent'].id == self.instance.id:
raise forms.ValidationError("You can't set the parent of the "
"item to itself.")
raise forms.ValidationError(_("You can't set the parent of the "
"item to itself."))
elif self.cleaned_data['parent'].id in decendant_ids:
raise forms.ValidationError("You can't set the parent of the "
"item to a descendant.")
raise forms.ValidationError(_("You can't set the parent of the "
"item to a descendant."))
return self.cleaned_data


Expand Down Expand Up @@ -144,7 +145,7 @@ def deactivate(self, request, queryset):
item.active = False
item.save()
item.children.all().update(active=False)
deactivate.short_description = "Deactivate selected categories and their children"
deactivate.short_description = _('Deactivate selected categories and their children')

def activate(self, request, queryset):
"""
Expand All @@ -157,4 +158,4 @@ def activate(self, request, queryset):
item.active = True
item.save()
item.children.all().update(active=True)
activate.short_description = "Activate selected categories and their children"
activate.short_description = _('Activate selected categories and their children')
30 changes: 19 additions & 11 deletions categories/migration.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from django.db import models, DatabaseError
from django.core.exceptions import ImproperlyConfigured
from django.utils.translation import ugettext_lazy as _


def migrate_app(sender, app, created_models, verbosity, *args, **kwargs):
Expand All @@ -17,7 +18,8 @@ def migrate_app(sender, app, created_models, verbosity, *args, **kwargs):
try:
from south.db import db
except ImportError:
raise ImproperlyConfigured("South must be installed for this command to work")
raise ImproperlyConfigured(_('%(dependency) must be installed for this command to work') %
{'dependency' : 'South'})
# pull the information from the registry
app_name = app.__name__.split('.')[-2]

Expand All @@ -38,17 +40,19 @@ def migrate_app(sender, app, created_models, verbosity, *args, **kwargs):
db.add_column(table_name, field_name, FIELD_REGISTRY[fld], keep_default=False)
db.commit_transaction()
if verbosity:
print "Added ForeignKey %s to %s" % (field_name, model_name)
print (_('Added ForeignKey %(field_name) to %(model_name)') %
{'field_name' : field_name, 'model_name' : model_name})
except DatabaseError, e:
db.rollback_transaction()
if "already exists" in str(e):
if verbosity > 1:
print "ForeignKey %s to %s already exists" % (field_name, model_name)
print (_('ForeignKey %(field_name) to %(model_name) already exists') %
{'field_name' : field_name, 'model_name' : model_name})
else:
sys.stderr = org_stderror
raise e
elif isinstance(FIELD_REGISTRY[fld], CategoryM2MField):
table_name = "%s_%s" % (mdl._meta.db_table, 'categories')
table_name = '%s_%s' % (mdl._meta.db_table, 'categories')
try:
db.start_transaction()
db.create_table(table_name, (
Expand All @@ -59,12 +63,14 @@ def migrate_app(sender, app, created_models, verbosity, *args, **kwargs):
db.create_unique(table_name, ['%s_id' % model_name, 'category_id'])
db.commit_transaction()
if verbosity:
print "Added Many2Many table between %s and %s" % (model_name, 'category')
print (_('Added Many2Many table between %(model_name) and %(category_table)') %
{'model_name' : model_name, 'category_table' : 'category'})
except DatabaseError, e:
db.rollback_transaction()
if "already exists" in str(e):
if verbosity > 1:
print "Many2Many table between %s and %s already exists" % (model_name, 'category')
print (_('Many2Many table between %(model_name) and %(category_table) already exists') %
{'model_name' : model_name, 'category_table' : 'category'})
else:
sys.stderr = org_stderror
raise e
Expand All @@ -82,13 +88,15 @@ def drop_field(app_name, model_name, field_name):
try:
from south.db import db
except ImportError:
raise ImproperlyConfigured("South must be installed for this command to work")
raise ImproperlyConfigured(_('%(dependency) must be installed for this command to work') %
{'dependency' : 'South'})
mdl = models.get_model(app_name, model_name)

fld = "%s.%s.%s" % (app_name, model_name, field_name)
fld = '%s.%s.%s' % (app_name, model_name, field_name)

if isinstance(FIELD_REGISTRY[fld], CategoryFKField):
print "Dropping ForeignKey %s from %s" % (field_name, model_name)
print (_('Dropping ForeignKey %(field_name) from %(model_name)') %
{'field_name' : field_name, 'model_name' : model_name})
try:
db.start_transaction()
table_name = mdl._meta.db_table
Expand All @@ -98,8 +106,8 @@ def drop_field(app_name, model_name, field_name):
db.rollback_transaction()
raise e
elif isinstance(FIELD_REGISTRY[fld], CategoryM2MField):
print "Dropping Many2Many table between %s and %s" % (model_name, 'category')
table_name = "%s_%s" % (mdl._meta.db_table, 'categories')
print (_('Dropping Many2Many table between %(model_name) and %(category_table)') %
{'model_name' : model_name, 'category_table' : 'category'})
try:
db.start_transaction()
db.delete_table(table_name, cascade=False)
Expand Down
11 changes: 6 additions & 5 deletions categories/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,8 @@ def save(self, *args, **kwargs):
super(Category, self).save(*args, **kwargs)

class Meta(CategoryBase.Meta):
verbose_name_plural = 'categories'
verbose_name = _('category')
verbose_name_plural = _('categories')

class MPTTMeta:
order_insertion_by = ('order', 'name')
Expand Down Expand Up @@ -118,12 +119,12 @@ def get_relation_type(self, relation_type):

class CategoryRelation(models.Model):
"""Related category item"""
category = models.ForeignKey(Category)
category = models.ForeignKey(Category, verbose_name=_('category'))
content_type = models.ForeignKey(
ContentType, limit_choices_to=CATEGORY_RELATION_LIMITS)
object_id = models.PositiveIntegerField()
ContentType, limit_choices_to=CATEGORY_RELATION_LIMITS, verbose_name=_('content type'))
object_id = models.PositiveIntegerField(verbose_name=_('object id'))
content_object = generic.GenericForeignKey('content_type', 'object_id')
relation_type = models.CharField(_("Relation Type"),
relation_type = models.CharField(verbose_name=_('relation type'),
max_length="200",
blank=True,
null=True,
Expand Down
8 changes: 5 additions & 3 deletions categories/registration.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def _process_registry(registry, call_func):
for key, value in registry.items():
model = get_model(*key.split('.'))
if model is None:
raise ImproperlyConfigured('%s is not a model' % key)
raise ImproperlyConfigured(_('%(key) is not a model') % {'key' : key})
if isinstance(value, (tuple, list)):
for item in value:
if isinstance(item, basestring):
Expand All @@ -51,11 +51,13 @@ def _process_registry(registry, call_func):
field_name = item.pop('name')
call_func(model, field_name, extra_params=item)
else:
raise ImproperlyConfigured("CATEGORY_SETTINGS doesn't recognize the value of %s" % key)
raise ImproperlyConfigured(_("%(settings) doesn't recognize the value of %(key)") %
{'settings' : 'CATEGORY_SETTINGS', 'key' : key})
elif isinstance(value, basestring):
call_func(model, value)
elif isinstance(value, dict):
field_name = value.pop('name')
call_func(model, field_name, extra_params=value)
else:
raise ImproperlyConfigured("CATEGORY_SETTINGS doesn't recognize the value of %s" % key)
raise ImproperlyConfigured(_("%(settings) doesn't recognize the value of %(key)") %
{'settings' : 'CATEGORY_SETTINGS', 'key' : key})
16 changes: 10 additions & 6 deletions categories/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from django.conf import settings
from django.db.models import Q
from django.utils.translation import ugettext_lazy as _

DEFAULT_SETTINGS = {
'ALLOW_SLUG_CHANGE': False,
Expand Down Expand Up @@ -29,26 +30,29 @@
DEFAULT_SETTINGS['SLUG_TRANSLITERATOR'] = getattr(module, bits[-1])
else:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured("SLUG_TRANSLITERATOR must be a callable or a string.")
raise ImproperlyConfigured(_('%(transliterator) must be a callable or a string.') %
{'transliterator' : 'SLUG_TRANSLITERATOR'})
else:
DEFAULT_SETTINGS['SLUG_TRANSLITERATOR'] = lambda x: x

ERR_MSG = "settings.%s is deprecated; use settings.CATEGORIES_SETTINGS instead."
def warn_deprecated(deprecated_setting, replacement):
warnings.warn(_('%(deprecated_setting) is deprecated; use %(replacement)s instead.') %
{'deprecated_setting' : deprecated_setting, 'replacement' : replacement}, DeprecationWarning)

if hasattr(settings, 'CATEGORIES_ALLOW_SLUG_CHANGE'):
warnings.warn(ERR_MSG % 'CATEGORIES_ALLOW_SLUG_CHANGE', DeprecationWarning)
warn_deprecated('settings.CATEGORIES_ALLOW_SLUG_CHANGE', 'settings.CATEGORIES_SETTINGS')
DEFAULT_SETTINGS["ALLOW_SLUG_CHANGE"] = getattr(settings, 'CATEGORIES_ALLOW_SLUG_CHANGE')

if hasattr(settings, 'CATEGORIES_CACHE_VIEW_LENGTH'):
warnings.warn(ERR_MSG % "CATEGORIES_CACHE_VIEW_LENGTH", DeprecationWarning)
warn_deprecated('settings.CATEGORIES_CACHE_VIEW_LENGTH', 'settings.CATEGORIES_SETTINGS')
DEFAULT_SETTINGS["CACHE_VIEW_LENGTH"] = getattr(settings, 'CATEGORIES_CACHE_VIEW_LENGTH')

if hasattr(settings, 'CATEGORIES_THUMBNAIL_UPLOAD_PATH'):
warnings.warn(ERR_MSG % "CATEGORIES_THUMBNAIL_UPLOAD_PATH", DeprecationWarning)
warn_deprecated('settings.CATEGORIES_THUMBNAIL_UPLOAD_PATH', 'settings.CATEGORIES_SETTINGS')
DEFAULT_SETTINGS["THUMBNAIL_UPLOAD_PATH"] = getattr(settings, 'CATEGORIES_THUMBNAIL_UPLOAD_PATH')

if hasattr(settings, 'CATEGORIES_RELATION_MODELS'):
warnings.warn(ERR_MSG % "CATEGORIES_RELATION_MODELS", DeprecationWarning)
warn_deprecated('settings.CATEGORIES_RELATION_MODELS', 'settings.CATEGORIES_SETTINGS')
DEFAULT_SETTINGS["RELATION_MODELS"] = getattr(settings, 'CATEGORIES_RELATION_MODELS')

# Add all the keys/values to the module's namespace
Expand Down
6 changes: 3 additions & 3 deletions categories/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,14 +70,14 @@ class CategoryDetailView(DetailView):

def get_object(self, **kwargs):
if self.path_field not in self.kwargs:
raise AttributeError(u"Category detail view %s must be called with "
u"a %s." % self.__class__.__name__, self.path_field)
raise AttributeError(_('Category detail view %(view) must be called with a %(path_field).') %
{'view' : self.__class__.__name__, 'path_field' : self.path_field})
if self.queryset is None:
queryset = self.get_queryset()
try:
return get_category_for_path(self.kwargs[self.path_field])
except ObjectDoesNotExist:
raise Http404(_(u"No %(verbose_name)s found matching the query") %
raise Http404(_('No %(verbose_name)s found matching the query') %
{'verbose_name': queryset.model._meta.verbose_name})

def get_template_names(self):
Expand Down

0 comments on commit 89c7333

Please sign in to comment.