Django gettext not working properly with django rest #9075
Replies: 1 comment
-
The issue you're encountering with inconsistent translation of CharField choices in a ModelSerializer is likely related to how Django handles translations and gettext on Windows, as you've mentioned. Translations can sometimes behave differently on Windows compared to other platforms due to encoding and path issues. The workaround you've provided by using SerializerMethodField and explicitly translating the choice values using _() should indeed work, but it's not the most elegant solution. It's important to note that using _() to translate model field choices directly in model definitions doesn't always work reliably, especially on Windows. Use ugettext_lazy: Instead of using gettext, consider using ugettext_lazy for translating the choice values in the model field. ugettext_lazy is a lazy evaluation version of ugettext that's used to translate strings in models. `from django.utils.translation import ugettext_lazy as _ class YourModel(models.Model): OR Use a Separate Translations File: Create a separate translations file for your model field choices. This can help isolate and manage the translations more effectively. You can create a choices.py file in your app's locale directory and define the translations there. For example, in your_app/locale/choices.py: your_app/locale/choices.py` CHOICES_TRANSLATIONS = { `from .locale.choices import CHOICES_TRANSLATIONS class YourModel(models.Model): |
Beta Was this translation helpful? Give feedback.
-
I'm having some weird bug with gettext while using a ModelSerializer, I cannot get the translated charfield choice for all of the choices, some choices work but others don't I even tried to run another
makemessages
command but the same inconsistent result.this is the problematic field
My solution was this but I don't think it's a decent one
the solution to this was using
get_FieldName_display()
something like this worked correctly:this is probably because i'm using windows
Any ideas about this ?
Beta Was this translation helpful? Give feedback.
All reactions