From 6f7704bc57ef5eb8467b92a3092aea222d596735 Mon Sep 17 00:00:00 2001 From: Dirk Eschler Date: Wed, 4 Jul 2012 10:09:22 +0000 Subject: [PATCH] Some cleanups and validated codebase against PEP8 and coding guidelines. --- modeltranslation/admin.py | 4 +- modeltranslation/fields.py | 28 ++++++---- .../commands/update_translation_fields.py | 18 +++---- modeltranslation/settings.py | 18 +++---- modeltranslation/translator.py | 53 +++++++++---------- modeltranslation/utils.py | 4 +- 6 files changed, 64 insertions(+), 61 deletions(-) diff --git a/modeltranslation/admin.py b/modeltranslation/admin.py index 0f2d212..86e3cab 100644 --- a/modeltranslation/admin.py +++ b/modeltranslation/admin.py @@ -142,7 +142,7 @@ class TranslationBaseModelAdmin(BaseModelAdmin): if exclude_languages is None: exclude_languages = [] if exclude_languages: - excl_languages = exclude_languages + excl_languages = exclude_languages else: for lang in self.exclude_languages: # TODO: Not a good place for validation. @@ -177,7 +177,7 @@ class TranslationBaseModelAdmin(BaseModelAdmin): exclude_fields = tuple(self.exclude) + tuple(exclude_fields) if exclude_fields: kwargs.update({'exclude': getattr( - kwargs, 'exclude', tuple()) + exclude_fields,}) + kwargs, 'exclude', tuple()) + exclude_fields}) if kwargs.get('exclude_languages'): del kwargs['exclude_languages'] return kwargs diff --git a/modeltranslation/fields.py b/modeltranslation/fields.py index b26892c..974f0f6 100644 --- a/modeltranslation/fields.py +++ b/modeltranslation/fields.py @@ -28,7 +28,7 @@ def create_translation_field(model, field_name, lang): field = model._meta.get_field(field_name) cls_name = field.__class__.__name__ # No subclass required for text-like fields - if not (isinstance(field, (CharField, TextField)) or\ + if not (isinstance(field, (CharField, TextField)) or cls_name in CUSTOM_FIELDS): raise ImproperlyConfigured('%s is not supported by ' 'modeltranslation.' % cls_name) @@ -60,7 +60,9 @@ class TranslationField(Field): self._post_init(translated_field, language) def _post_init(self, translated_field, language): - """Common init for subclasses of TranslationField.""" + """ + Common init for subclasses of TranslationField. + """ # Store the originally wrapped field for later self.translated_field = translated_field self.language = language @@ -77,8 +79,8 @@ class TranslationField(Field): # Copy the verbose name and append a language suffix # (will show up e.g. in the admin). - self.verbose_name =\ - build_localized_verbose_name(translated_field.verbose_name, language) + self.verbose_name = build_localized_verbose_name( + translated_field.verbose_name, language) def pre_save(self, model_instance, add): val = super(TranslationField, self).pre_save(model_instance, add) @@ -103,7 +105,9 @@ class TranslationField(Field): return self.translated_field.get_internal_type() def south_field_triple(self): - """Returns a suitable description of this field for South.""" + """ + Returns a suitable description of this field for South. + """ # We'll just introspect the _actual_ field. from south.modelsinspector import introspector field_class = '%s.%s' % (self.translated_field.__class__.__module__, @@ -113,7 +117,9 @@ class TranslationField(Field): return (field_class, args, kwargs) def formfield(self, *args, **kwargs): - """Preserves the widget of the translated field.""" + """ + Preserves the widget of the translated field. + """ trans_formfield = self.translated_field.formfield(*args, **kwargs) defaults = {'widget': type(trans_formfield.widget)} defaults.update(kwargs) @@ -121,8 +127,10 @@ class TranslationField(Field): class TranslationFieldDescriptor(object): - """A descriptor used for the original translated field.""" - def __init__(self, name, initial_val="", fallback_value=None): + """ + A descriptor used for the original translated field. + """ + def __init__(self, name, initial_val='', fallback_value=None): """ The ``name`` is the name of the field (which is not available in the descriptor by default - this is Python behaviour). @@ -144,8 +152,8 @@ class TranslationFieldDescriptor(object): if not instance: raise ValueError(u"Translation field '%s' can only be accessed " "via an instance not via a class." % self.name) - loc_field_name = build_localized_fieldname(self.name, - get_language()) + loc_field_name = build_localized_fieldname( + self.name, get_language()) if hasattr(instance, loc_field_name): if getattr(instance, loc_field_name): return getattr(instance, loc_field_name) diff --git a/modeltranslation/management/commands/update_translation_fields.py b/modeltranslation/management/commands/update_translation_fields.py index 34c9fd8..7ac5a26 100644 --- a/modeltranslation/management/commands/update_translation_fields.py +++ b/modeltranslation/management/commands/update_translation_fields.py @@ -10,18 +10,18 @@ from modeltranslation.utils import build_localized_fieldname class Command(NoArgsCommand): - help = 'Updates the default translation fields of all or the specified'\ - 'translated application using the value of the original field.' + help = ('Updates the default translation fields of all or the specified' + 'translated application using the value of the original field.') def handle(self, **options): print "Using default language:", DEFAULT_LANGUAGE for model, trans_opts in translator._registry.items(): print "Updating data of model '%s'" % model for fieldname in trans_opts.fields: - def_lang_fieldname =\ - build_localized_fieldname(fieldname, DEFAULT_LANGUAGE) - - # We'll only update fields which do not have an existing value: - model.objects.filter(Q(**{def_lang_fieldname: None}) |\ - Q(**{def_lang_fieldname: ""})).update(\ - **{def_lang_fieldname: F(fieldname)}) + def_lang_fieldname = build_localized_fieldname( + fieldname, DEFAULT_LANGUAGE) + # We'll only update fields which do not have an existing value + model.objects.filter( + Q(**{def_lang_fieldname: None}) | + Q(**{def_lang_fieldname: ""})).update( + **{def_lang_fieldname: F(fieldname)}) diff --git a/modeltranslation/settings.py b/modeltranslation/settings.py index 4a66b63..e534308 100644 --- a/modeltranslation/settings.py +++ b/modeltranslation/settings.py @@ -7,16 +7,16 @@ from django.core.exceptions import ImproperlyConfigured if hasattr(settings, 'MODELTRANSLATION_TRANSLATION_REGISTRY'): - TRANSLATION_REGISTRY =\ - getattr(settings, 'MODELTRANSLATION_TRANSLATION_REGISTRY', None) + TRANSLATION_REGISTRY = getattr( + settings, 'MODELTRANSLATION_TRANSLATION_REGISTRY', None) elif hasattr(settings, 'TRANSLATION_REGISTRY'): warn('The setting TRANSLATION_REGISTRY is deprecated, use ' 'MODELTRANSLATION_TRANSLATION_REGISTRY instead.', DeprecationWarning) TRANSLATION_REGISTRY = getattr(settings, 'TRANSLATION_REGISTRY', None) else: - raise ImproperlyConfigured("You haven't set the " - "MODELTRANSLATION_TRANSLATION_REGISTRY " - "setting yet.") + raise ImproperlyConfigured( + "You haven't set the MODELTRANSLATION_TRANSLATION_REGISTRY " + "setting yet.") AVAILABLE_LANGUAGES = [l[0] for l in settings.LANGUAGES] DEFAULT_LANGUAGE = getattr(settings, 'MODELTRANSLATION_DEFAULT_LANGUAGE', None) @@ -27,12 +27,10 @@ elif not DEFAULT_LANGUAGE: DEFAULT_LANGUAGE = AVAILABLE_LANGUAGES[0] # FIXME: We can't seem to override this particular setting in tests.py -CUSTOM_FIELDS =\ -getattr(settings, 'MODELTRANSLATION_CUSTOM_FIELDS', ()) +CUSTOM_FIELDS = getattr(settings, 'MODELTRANSLATION_CUSTOM_FIELDS', ()) try: if sys.argv[1] == 'test': - CUSTOM_FIELDS =\ - getattr(settings, 'MODELTRANSLATION_CUSTOM_FIELDS', - ('BooleanField',)) + CUSTOM_FIELDS = getattr( + settings, 'MODELTRANSLATION_CUSTOM_FIELDS', ('BooleanField',)) except IndexError: pass diff --git a/modeltranslation/translator.py b/modeltranslation/translator.py index 48feac0..ca07008 100644 --- a/modeltranslation/translator.py +++ b/modeltranslation/translator.py @@ -45,20 +45,19 @@ def add_localized_fields(model): localized_fields[field_name] = list() for l in settings.LANGUAGES: # Create a dynamic translation field - translation_field = create_translation_field(model=model,\ - field_name=field_name, lang=l[0]) + translation_field = create_translation_field( + model=model, field_name=field_name, lang=l[0]) # Construct the name for the localized field localized_field_name = build_localized_fieldname(field_name, l[0]) # Check if the model already has a field by that name if hasattr(model, localized_field_name): - raise ValueError("Error adding translation field. Model '%s' " - "already contains a field named '%s'." %\ - (instance.__class__.__name__, - localized_field_name)) + raise ValueError( + "Error adding translation field. Model '%s' already " + "contains a field named '%s'." % ( + instance.__class__.__name__, localized_field_name)) # This approach implements the translation fields as full valid # django model fields and therefore adds them via add_to_class - localized_field = model.add_to_class(localized_field_name, - translation_field) + model.add_to_class(localized_field_name, translation_field) localized_fields[field_name].append(localized_field_name) return localized_fields @@ -115,10 +114,10 @@ class Translator(object): AlreadyRegistered. """ # Don't import the humongous validation code unless required - if translation_opts and settings.DEBUG: - from django.contrib.admin.validation import validate - else: - validate = lambda model, adminclass: None + #if translation_opts and settings.DEBUG: + #from django.contrib.admin.validation import validate + #else: + #validate = lambda model, adminclass: None #if not translation_opts: #translation_opts = TranslationOptions @@ -137,8 +136,8 @@ class Translator(object): # the created class appears to "live" in the wrong place, # which causes issues later on. options['__module__'] = __name__ - translation_opts = type("%sAdmin" % model.__name__, - (translation_opts,), options) + translation_opts = type( + "%sAdmin" % model.__name__, (translation_opts,), options) # Validate (which might be a no-op) #validate(translation_opts, model) @@ -146,11 +145,6 @@ class Translator(object): # Store the translation class associated to the model self._registry[model] = translation_opts - # Get the content type of the original model and store it on the - # translation options for faster lookup later on. - #translation_opts.model_ct = \ - #ContentType.objects.get_for_model(model) - # Add the localized fields to the model and store the names of # these fields in the model's translation options for faster lookup # later on. @@ -159,7 +153,7 @@ class Translator(object): # Create a reverse dict mapping the localized_fieldnames to the # original fieldname rev_dict = dict() - for orig_name, loc_names in\ + for orig_name, loc_names in \ translation_opts.localized_fieldnames.items(): for ln in loc_names: rev_dict[ln] = orig_name @@ -169,18 +163,18 @@ class Translator(object): for related_obj in model._meta.get_all_related_objects(): delete_cache_fields(related_obj.model) - model_fallback_values =\ - getattr(translation_opts, 'fallback_values', None) + model_fallback_values = getattr( + translation_opts, 'fallback_values', None) for field_name in translation_opts.fields: if model_fallback_values is None: field_fallback_value = None elif isinstance(model_fallback_values, dict): - field_fallback_value =\ - model_fallback_values.get(field_name, None) + field_fallback_value = model_fallback_values.get( + field_name, None) else: field_fallback_value = model_fallback_values - setattr(model, field_name, TranslationFieldDescriptor(field_name,\ - fallback_value=field_fallback_value)) + setattr(model, field_name, TranslationFieldDescriptor( + field_name, fallback_value=field_fallback_value)) #signals.pre_init.connect(translated_model_initializing, sender=model, #weak=False) @@ -227,10 +221,11 @@ class Translator(object): '__module__': __name__, 'fields': tuple(fields), 'localized_fieldnames': localized_fieldnames, - 'localized_fieldnames_rev': localized_fieldnames_rev, + 'localized_fieldnames_rev': localized_fieldnames_rev } - translation_opts = type("%sTranslation" % model.__name__, - (TranslationOptions,), options) + translation_opts = type( + "%sTranslation" % model.__name__, + (TranslationOptions,), options) # delete_cache_fields(model) return translation_opts raise NotRegistered('The model "%s" is not registered for ' diff --git a/modeltranslation/utils.py b/modeltranslation/utils.py index f86b010..7c3484f 100644 --- a/modeltranslation/utils.py +++ b/modeltranslation/utils.py @@ -19,7 +19,9 @@ def get_language(): def get_translation_fields(field): - """Returns a list of localized fieldnames for a given field.""" + """ + Returns a list of localized fieldnames for a given field. + """ return [build_localized_fieldname(field, l) for l in AVAILABLE_LANGUAGES]