How can you solve the problem of separating the output text and code, and write only the key in the code?

Task: It is necessary to remove all the text from the code and from the template is valid in the json file.

At the moment there is such a solution:

{ 'sc.site_name' : 'Site name', 'sc.phone_number' : 'Phone number', 'sc.email' : 'E-mail', 'sc.skype' : 'Skype', } 

And an example in the model:

 class SiteConfiguration(SingletonModel): site_name = models.CharField(verbose_name = json_local['sc.site_name']) phone_number = PhoneNumberField(verbose_name = json_local['sc.phone_number']) email = models.EmailField(verbose_name = json_local['sc.email']) skype = models.CharField(verbose_name = json_local['sc.skype']) 

Completed the question:

Perhaps a similar approach to use in conjunction with gettext? I may not understand why gettext is needed, but how effective is it in terms of performance and convenience to store text in * .po files and use keys in msgid?

Example of structure in JSON (for illustrative example):

 { 'sc.site_name': { 'ru': 'Имя сайта', 'us': 'Site name', ... } ... } 

And in the file * .po:

 # ru.po msgid "sc.site_name" msgstr "Название сайта" # us.po msgid "sc.site_name" msgstr "Site name" 
  • one
    In janga there are all the built-in tools for internationalization with gettext, described in detail in the official textbook, why not use them? Only instead of English phrases to use these keys - andreymal
  • @andreymal is what interests me exactly how much to use the place of the phrase key - users
  • In general, this seems to be wrong irrespective of the specific implementation (for if the wording changes a little, but the key does not change, it is very easy to forget to correct the wording in all languages, while using the English phrase as a key, it will change and all utilities for translations will declare incomplete translation, it becomes difficult to forget), but many people do the same to them, and using a key with gettext or without gettext doesn’t seem to make a fundamental difference, but if it comes with django out of the box, then why not) andreymal

2 answers 2

You can also use the get () method for this task, it differs in that you will not get a KeyError , in case you forget to specify a value. The result will be None or what you specified as the second argument.

 json_local.get('sc.site_name', 'default_field_name') 

You can also store strings in a separate module as variables and import this module where necessary.

    Solution using gettext, in the code I use keys:

     from django.utils.translation import ugettext_lazy as _ text = _("sc.site_name") 

    And I assign the key a line in the * .po files:

     # ru.po msgid "sc.site_name" msgstr "Название сайта" # us.po msgid "sc.site_name" msgstr "Site name"