Gasim Gasim - 4 years ago 82
Python Question

django parler create test objects

I have models that have translatable fields using Django Parler and now I am trying to create objects for unit testing. Here is an example model that I have

class Federation(TranslatableModel):
translations = TranslatedFields(
name = models.CharField('name', max_length=50)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)

creator = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, related_name='federation_creator')
updater = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, related_name='federation_updater')

def __str__(self):

Now I want to create objects for testing during setUp phase of test case:


but I don't know how to create objects with translatable fields.

How can I achieve this?

Answer Source

You can do this in the way the Parler documentation suggests throughout:

f = Federation()

f.set_current_language('en') = 'The British'

f.set_current_language('en') = 'Les rosbifs'

But you can also do:

f = Federation.objects.language('en').create(
    name='The British',

f.set_current_language('en') = 'Les rosbifs'

which is what you're asking about and is more elegant, especially if you only have one language version to create.

I discovered the language('en') method here:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download