Skip to content

Instantly share code, notes, and snippets.

@larryng
Created April 5, 2012 18:19
Show Gist options
  • Save larryng/2312981 to your computer and use it in GitHub Desktop.
Save larryng/2312981 to your computer and use it in GitHub Desktop.
Some Django glue to make factory-boy work with modeltranslation. Tested with python 2.7.2, django 1.3.1, factory-boy 1.1.3, and django-modeltranslation 0.3.3
import factory
import modeltranslation
class ModelTranslationFactory(factory.DjangoModelFactory):
"""Abstract Factory for models registered with modeltranslation.
Factories inheriting this produce objects with fields that adhere to the
'Rules for translated field access' specified by modeltranslation.
See:
http://code.google.com/p/django-modeltranslation/wiki/InstallationAndUsage
"""
ABSTRACT_FACTORY = True
@classmethod
def _prepare(cls, create, **kwargs):
trans_fields = modeltranslation.translator.translator._registry[cls._associated_class].fields
for field in trans_fields:
tfield = '{0}_{1}'.format(field, modeltranslation.settings.DEFAULT_LANGUAGE)
if field in kwargs:
kwargs[tfield] = kwargs[field]
elif tfield in kwargs:
kwargs[field] = kwargs[tfield]
return super(ModelTranslationFactory, cls)._prepare(create, **kwargs)
@ismailsunni
Copy link

I tried to make it work with Django 1.8, django-modeltranslation 0.12.2, factory-boy 2.10, but no luck.

@ismailsunni
Copy link

For anyone who stumbles here, you can still use factoryboy for unit testing. Just put in mind that factory boy doesn't update the initial values for other languages. You can update your other languages value, by using:

with translation.override('id'):
    model.title = indonesian_title
    model.save()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment