Commits

Anonymous committed 8142745

Code cleanups.

Comments (0)

Files changed (10)

modeltranslation/admin.py

 # -*- coding: utf-8 -*-
 from copy import deepcopy
 
+from django import forms, template
 from django.conf import settings
 from django.contrib import admin
 from django.contrib.contenttypes.models import ContentType
 from django.forms import widgets
-from django import forms, template
 from django.forms.fields import MultiValueField
 from django.shortcuts import get_object_or_404, render_to_response
 from django.utils.safestring import mark_safe

modeltranslation/fields.py

 # -*- coding: utf-8 -*-
 from django.conf import settings
 from django.db.models.fields import Field, CharField
+
 from modeltranslation.utils import get_language, build_localized_fieldname
 
 class TranslationField(Field):
     descriptor.
     
     The translation field needs to know which language it contains therefore
-    that needs to be specified when the field is created.            
+    that needs to be specified when the field is created.
+    
     """
     def __init__(self, translated_field, language, *args, **kwargs):
         # Store the originally wrapped field for later
         self.blank = True
         
         # Adjust the name of this field to reflect the language
-        self.attname = build_localized_fieldname(translated_field.name, language)
+        self.attname = build_localized_fieldname(translated_field.name,
+                                                 language)
         self.name = self.attname
         
         # Copy the verbose name and append a language suffix (will e.g. in the
             #return orig_val
         return val
                     
-    #def get_attname(self):
-        #return self.attname       
-                
     def get_internal_type(self):
         return self.translated_field.get_internal_type()
         
         """
         # We'll just introspect the _actual_ field.
         from south.modelsinspector import introspector
-        field_class = self.translated_field.__class__.__module__ + "." + self.translated_field.__class__.__name__
+        field_class = '%s.%s' % (self.translated_field.__class__.__module__,
+                                 self.translated_field.__class__.__name__)
         args, kwargs = introspector(self.translated_field)
         # That's our definition!
         return (field_class, args, kwargs)

modeltranslation/management/commands/update_translation_fields.py

-
+# -*- coding: utf-8 -*-
 from django.conf import settings
 from django.core.management.base import BaseCommand, CommandError, NoArgsCommand
 
 from modeltranslation.utils import build_localized_fieldname
 
 class Command(NoArgsCommand):
-    help = 'Updates the default translation fields of all or the specified'\
+    help = 'Updates the default translation fields of all or the specified' \
            'translated application using the value of the original field.'
-    # args = '[app_name]'
         
     def handle(self, **options):        
         default_lang = settings.LANGUAGES[0][0]        

modeltranslation/middleware.py

-# from django.db.models import signals
-# from django.utils.functional import curry
-
-#class TranslationMiddleware(object):
-    #def process_request(self, request):
-        #if hasattr(request, 'LANGUAGE_CODE'):
-            #print "TranslationMiddleware: preferred lang=", request.LANGUAGE_CODE
-            #update_lang = curry(self.update_lang, request.LANGUAGE_CODE)
-            #signals.pre_save.connect(update_lang, dispatch_uid=request, weak=False)
-        #else:
-            #print "TranslationMiddleware: no lang"
-            #pass
-    
-    
-    #def update_lang(self, lang, sender, instance, **kwargs):
-        #registry = registration.FieldRegistry()
-        #if sender in registry:
-            #for field in registry.get_fields(sender):
-                #setattr(instance, field.name, lang)                
-    
-    #def process_response(self, request, response):
-        #print "response:", dir(response)
-        #signals.pre_save.disconnect(dispatch_uid=request)
-        #return response

modeltranslation/models.py

 # -*- coding: utf-8 -*-
 import sys
+
+from django.conf import settings
 from django.db import models
-from django.conf import settings
+
 from modeltranslation.translator import translator
 
 # Every model registered with the modeltranslation.translator.translator
             translated_model_names = ', '.join(
                 t.__name__ for t in translator._registry.keys())
             print "modeltranslation: Registered %d models for translation " \
-                  "(%s)." % (len(translator._registry), translated_model_names)
+                  "(%s)." % (len(translator._registry),
+                             translated_model_names)
     except IndexError:
         pass

modeltranslation/tests.py

 # -*- coding: utf-8 -*-
 from django.conf import settings
+from django.contrib.auth.models import User
 from django.contrib.contenttypes.models import ContentType
 from django.db import models
 from django.test import TestCase
-from django.contrib.auth.models import User
+from django.utils.thread_support import currentThread
 from django.utils.translation import get_language
 from django.utils.translation import trans_real
-from django.utils.thread_support import currentThread
 
 from modeltranslation import translator
 
 settings.LANGUAGES = (('de', 'Deutsch'),
                       ('en', 'English'))
 
+
 class TestModel(models.Model):
     title = models.CharField(max_length=255)
     text = models.TextField(null=True)
 
+
 class TestTranslationOptions(translator.TranslationOptions):
     fields = ('title', 'text',)
 
+
 translator.translator._registry = {}
 translator.translator.register(TestModel, TestTranslationOptions)
 
+
 class ModelTranslationTest(TestCase):    
-    "Basic tests for the modeltranslation application."
+    """Basic tests for the modeltranslation application."""
     
     urls = 'modeltranslation.testurls'
     
         self.failUnlessEqual(len(translator.translator._registry), 1)
                 
         # Try to unregister a model that is not registered
-        self.assertRaises(translator.NotRegistered, translator.translator.unregister, User)
+        self.assertRaises(translator.NotRegistered,
+                          translator.translator.unregister, User)
                         
         # Try to get options for a model that is not registered
-        self.assertRaises(translator.NotRegistered, translator.translator.get_options_for_model, User)
+        self.assertRaises(translator.NotRegistered,
+                          translator.translator.get_options_for_model, User)
                 
-                            
     def test_translated_models(self):        
         # First create an instance of the test model to play with
-        inst = TestModel.objects.create(title="Testtitle", text="Testtext")        
+        inst = TestModel.objects.create(title="Testtitle", text="Testtext")
         field_names = dir(inst)
         self.failUnless('id' in field_names)
         self.failUnless('title' in field_names)
         # First create an instance of the test model to play with
         title1_de = "title de"
         title1_en = "title en"
-        title2_de = "title2 de"        
+        title2_de = "title2 de"
         inst1 = TestModel(title_en=title1_en, text="Testtext")
         inst1.title = title1_de
-        inst2 = TestModel(title=title2_de, text="Testtext")        
+        inst2 = TestModel(title=title2_de, text="Testtext")
         inst1.save()
         inst2.save()
         
         self.failUnlessEqual(n.text, text_de)
         trans_real.deactivate()
                 
-                
     def test_rule2(self):                                            
         """
         Rule 2: Assigning a value to the original field also updates the value
         
         trans_real.deactivate()                
                 
-                
     def test_rule3(self):
         """
         Rule 3: Assigning a value to a translation field of the default language
         self.failUnlessEqual(n.title, n.title_en)
         trans_real.deactivate()
                 
-            
     def test_rule4(self):                                
         """
         Rule 4: If both fields - the original and the translation field of the 

modeltranslation/testurls.py

-
+# -*- coding: utf-8 -*-
 from django.conf.urls.defaults import *
-from django.contrib import admin
-from django.views.generic.simple import direct_to_template
 
 urlpatterns = patterns('',
-
-    url(r'^set_language/$',
-        'django.views.i18n.set_language',
-        {},
+    url(r'^set_language/$', 'django.views.i18n.set_language', {},
         name='set_language'),
-    
-)
+)

modeltranslation/translator.py

+# -*- coding: utf-8 -*-
 from django.conf import settings
 #from django.contrib.contenttypes.models import ContentType
 from django.db import models
 
 class AlreadyRegistered(Exception):
     pass
+    
 
 class NotRegistered(Exception):
     pass
 
+
 class TranslationOptions(object):
     """
     The TranslationOptions object is used to specify the fields to translate.
         # self.translation_model = None
         #self.model_ct = None
         self.localized_fieldnames = list()
-        
-#def get_localized_fieldnames(model):
-        
+
+
 def add_localized_fields(model):
     """
     Monkey patchs the original model class to provide additional fields for 
     every language. Only do that for fields which are defined in the 
     translation options of the model.
     
-    Returns a dict mapping the original fieldname to a list containing the names 
-    of the localized fields created for the original field.
+    Returns a dict mapping the original fieldname to a list containing the
+    names of the localized fields created for the original field.
     """
     localized_fields = dict()
     translation_opts = translator.get_options_for_model(model)
             if hasattr(model, localized_field_name):
                 raise ValueError("Error adding translation field. The model "\
                                  "'%s' already contains a field named '%s'. "\
-                                 % (instance.__class__.__name__, localized_field_name))
+                                 % (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,
-                                                 TranslationField(model._meta.get_field(field_name), 
-                                                                  l[0]))             
+                                                 TranslationField(model._meta.get_field(field_name),
+                                                                  l[0]))
             localized_fields[field_name].append(localized_field_name)
-            
-        
     return localized_fields        
-    # model.add_to_class('current_language', CurrentLanguageField())        
+    
     
 #def translated_model_initialized(field_names, instance, **kwargs):
     #print "translated_model_initialized instance:", instance, ", field:", field_names
         #print "  field: %s, initialval: %s" % (field_name, initial_val)
         #setattr(instance.__class__, field_name, TranslationFieldDescriptor(field_name,
                                                                            #initial_val))
+                                                                           
+                                                                           
 #def translated_model_initializing(sender, args, kwargs, **signal_kwargs):
     #print "translated_model_initializing", sender, args, kwargs    
     #trans_opts = translator.get_options_for_model(sender)
         Unregisters the given model(s).
 
         If a model isn't already registered, this will raise NotRegistered.
+        
         """
         if isinstance(model_or_iterable, ModelBase):
             model_or_iterable = [model_or_iterable]
         """
         Returns the translation options for the given ``model``. If the 
         ``model`` is not registered a ``NotRegistered`` exception is raised.
+        
         """
         try:
             return self._registry[model]

modeltranslation/utils.py

 def get_language():
     """
     Return an active language code that is guaranteed to be in
-    settings.LANGUAGES (Django does not seem to guarantee this for
-    us.)    
+    settings.LANGUAGES (Django does not seem to guarantee this for us.)
+    
     """
     lang = _get_language()
     available_languages = [l[0] for l in settings.LANGUAGES]
 
 
 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[0]) for l in settings.LANGUAGES]
 
 
 class TranslationFieldDescriptor(object):
-    """
-    A descriptor used for the original translated field.
-    """
+    """A descriptor used for the original translated field."""
     def __init__(self, name, initial_val=""):
         """
         The ``name`` is the name of the field (which is not available in the
         # descriptor
         instance.__dict__[self.name] = value
         
-
     def __get__(self, instance, owner):
         # print "Descriptor.__get__%s %s %s.%s: %s" % (id(instance), id(self), type(instance), self.name, self.val)
         if not instance:
    
    
 def copy_field(field):
-    """Instantiate a new field, with all of the values from the old one, except the    
+    """
+    Instantiate a new field, with all of the values from the old one, except the    
     to and to_field in the case of related fields.
     
     This taken from http://www.djangosnippets.org/snippets/442/
+    
     """    
     base_kw = dict([(n, getattr(field, n, '_null')) for n in models.fields.Field.__init__.im_func.func_code.co_varnames])
     if isinstance(field, models.fields.related.RelatedField):

modeltranslation/views.py

Empty file removed.