question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Model field translation overrides default langauge for both fields on save

See original GitHub issue

I have a model called ‘Status’ with one field, ‘name’.

I registered the model:

class Status(Model):
    def __str__(self):
        return self.name
    class Meta:
        verbose_name = _('Status')
        verbose_name_plural = _('Statuses')

    name = CharField(verbose_name=_('Status Name'), max_length=100)
@register(Status)
class StatusTranslationOptions(TranslationOptions):
    fields = ('name', )

I registered with and without admin:

class StatusAdmin(TranslationAdmin):
    pass

admin.site.register(Status, StatusAdmin)

I enabled English and Spanish translation and whichever I set my browser configuration to, that’s the language that will override the other.

image

I have other models in the same app that are similar that don’t override the same way.

Issue Analytics

  • State:open
  • Created 2 years ago
  • Comments:8

github_iconTop GitHub Comments

1reaction
t-manncommented, Jul 10, 2022

The problem is in the cache as it was mentioned by @kathmandu777 But the cache is not a cache like redis or memcache. The problem sits in the django.db.models.fields.Field.get_col that returns self.cached_col that is actually decorated by @cached_property from django.utils.functional.

The fast workaround that works for me was to create custom register decorator with cleaning field cached properties. I only tested that admin part works correctly thus there still may be some side effects.

Solution allows to fix an issue as quick as possible, specially for projects that are using old versions of the model translations library. I suppose that there is better way to fix this issue in new versions.

"""
Register Decorator Patch
"""

__all__ = [
    'register'
]

# Standard library imports.
import logging

# Related third party imports.
from django.db.models.base import ModelBase

# Local application/library specific imports.


log = logging.getLogger('modeltranslation_patch')


def register(model_or_iterable, raise_exceptions: bool = False, **options):
    """
    Patched decorator to fix issue https://github.com/deschler/django-modeltranslation/issues/593
    Decorator has 1 more parameter `raise_exceptions` that may be used to control exception raising
    in a case if field retrieve from model meta failed
    """
    from modeltranslation.translator import translator, TranslationOptions

    def wrapper(opts_class):
        if not issubclass(opts_class, TranslationOptions):
            raise ValueError('Wrapped class must subclass TranslationOptions.')

        # >>>>>>>>>>> PATCH BEGIN <<<<<<<<<<<<<<
        if isinstance(model_or_iterable, ModelBase):
            models = [model_or_iterable]
        else:
            models = model_or_iterable

        for cls in models:
            for f_name in opts_class.fields:
                try:
                    f_obj = cls._meta.get_field(f_name)
                except Exception as e:
                    if raise_exceptions:
                        raise e
                    log.exception(f'Failed to get field with name `{f_name}` on model {cls.__name__}:\n{e}')
                    continue

                if 'cached_col' in f_obj.__dict__:
                    del f_obj.__dict__['cached_col']

        # >>>>>>>>>>>  PATCH END  <<<<<<<<<<<<<<

        translator.register(models, opts_class, **options)
        return opts_class

    return wrapper

1reaction
last-partizancommented, Mar 8, 2022

I don’t remember any caching (but i just maintainer, not author). Better check source code yourself.

Read more comments on GitHub >

github_iconTop Results From Across the Web

default language value overrides translation field in admin
I am using Django model translation for the multi-linguistic site(English(default), Arabic, French), the problem is when saving data in django ...
Read more >
Rules for Translated Field Access - django-modeltranslation
If both fields - the original and the current language translation field - are updated at the same time, the current language translation...
Read more >
language value overrides translation field in admin-django
[Solved]-default language value overrides translation field in admin-django ... Try using modeltranslation.admin.TranslationAdmin instead of ModelAdmin for your ...
Read more >
Model field reference - Django documentation
If True , Django will store empty values as NULL in the database. Default is False . Avoid using null on string-based fields...
Read more >
How to translate/rename custom labels and fields in managed ...
To change custom field labels, go to Setup – Translation Workbench – Override. Select a package. If you have items to override in...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found