pythondjangogettext

Why does Django remove translations from django.po when using gettext inside f-strings


For some weird reason, Django removes the translations from django.po file, if I used gettext or gettext_lazy inside Formatted String Literals (F-Strings)!

ex:

from django.contrib.admin import admin
from django.utils.translation import gettext_lazy as _

class fooAdmin(admin.ModelAdmin):
    def bar(self, foo):
        return format_html(f'''{_("Variable")}: {value1}<br />''')

When I update the messages by python manage.py makemessages --all --symlinks Django removes the Variable from django.po translation file, as long as Variable is not being used anywhere else except in the code above!

Why is that?


Solution

  • This is a limitation of xgettext, which Django's translation machinery uses; it does not (as of this writing) yet support Python f-strings, and therefore doesn't know how to extract the string from inside them. See the end of this section in the Django docs.

    The reason it disappears from the django.po file is that when a previously existing source string goes away (as it effectively does here since xgettext no longer sees it), it is either turned into a commented obsolete string at the end of the .po file, or with the --no-obsolete parameter to makemessages, removed entirely.