Vadorequest
Vadorequest

Reputation: 18049

Reflection/Lookup on Django model doesn't find internationalized (shadow) fields

I use a CMS that does a mapping of my models through an API at runtime.

It works fine, except for localized fields, because I use https://django-modeltranslation.readthedocs.io/en/latest/registration.html which add "shadow" fields that are obviously not mapped (they're not present in the model itself, but added through "register")

Is there any way I can tell my model that it owns those fields? It can find the label field, but misses the label_fr and label_en which are dynamically added at runtime.

Here is the translation.py:

from modeltranslation.translator import translator, TranslationOptions

from tfp_backoffice.apps.org.models import Org


class OrgTranslationOptions(TranslationOptions):
  """
  See https://django-modeltranslation.readthedocs.io/en/latest/registration.html
  """
  fields = ('label',)
  required_languages = ('fr',)  # ex: {'de': ('title', 'text'), 'default': ('title',)}


translator.register(Org, OrgTranslationOptions)

I use https://github.com/jet-admin/jet-django and I noticed that the response of the /model_descriptions endpoint only returns the label field.

I suspect this being the code being called when calling the endpoint https://github.com/jet-admin/jet-django/blob/94b0bb1451e768c7c3b6dadf9830d982914fe6c9/jet_django/views/model_description.py#L12

Basically, I've installed django-modeltranslation and jet-django apps, the later serves an API that is consumed by JET Admin UI and is used to do the models lookup.

I don't know if my issue must be fixed in jet-django itself, or if django provides a feature for shadow fields like that.

Upvotes: 0

Views: 218

Answers (1)

dirkgroten
dirkgroten

Reputation: 20702

django-modeltranslation uses a registration approach, described here, which means all models are patched when you launch your django app the first time. After django-modeltranslation is initialised, Post._meta.fields contains the translated fields text_fr and text_de in addition to text.

Looking at jet-django, it seems a JetAdminModelDescription is also initialised when the app is launched, the actual model fields are retrieved here using Model._meta.get_fields().

So as long as jet-django is initialised after django-modeltranslations, the fields should be also available to JetAdmin.

Make sure you place jet-django after django-modeltranslation in your INSTALLED_APPS setting and it should work.

Upvotes: 1

Related Questions