Evgenii Legotckoi
Evgenii LegotckoiFeb. 10, 2022, 4:13 a.m.

Django - Lesson 057. Multilanguage support in MarkdownField with auto populate functionality

The article How to write auto populate field functionality described the simplest functionality of the MarkdownField field to support markdown syntax on a site with automatic generation of html content.

I did not immediately show advanced functionality to make it easier to understand what a Markdown-like field is like. But now I would like to expand this functionality to add support for multilingualism.


Statement of the task

Usually, to add multilingualism in Django sites, they use the ready-made django modeltranslation battery, so I will also use support for this battery in this field.

Implementation

In order to implement this, you need to check in the site settings (settings.py file) the presence of the connected application modeltranslation , and then generate the html content in the appropriate field with the selected language.

To properly implement support for this functionality, let's modify the set_html method from the article How to write an auto populate field functionality .

# -*- coding: utf-8 -*-

from django.conf import settings
from django.db import models
from django.db.models.signals import pre_save

from .utils import MarkdownWorker


class MarkdownField(models.TextField):
    """
    This field save markdown text with auto-populate text to html field.
    This field must be used with second text field for html content.
    This field support django-modeltranslation package.
    """

    def set_html(self, instance=None, update_fields=None, **kwargs):
        value = getattr(instance, self.attname)
        if value and len(value) > 0:
            languages = getattr(settings, "LANGUAGES", None)
            if 'modeltranslation' in settings.INSTALLED_APPS and self.name.endswith(tuple([code for code, language in languages])):
                instance.__dict__['{}_{}'.format(self.html_field, self.name[-2:])] = MarkdownWorker(value).get_text()
            else:
                instance.__dict__[self.html_field] = MarkdownWorker(value).get_text()

    # Program code from previoues article

When the set_html method is called, we check for the presence of the modeltranslation app in the site's settings, and that the field's markdown name ends in one of the languages registered on the site.
If the condition is true, then we set the generated html content to the html field with the language code that the MarkdownField name ends with. Otherwise, we set the content to a regular html_field.

Why does this work?

If you are not familiar with modeltranslation yet, then I will briefly describe the principle of operation of this battery, without a detailed process for using this battery. Because the official documentation seems exhaustive to me.

When registering a field as multilingual using modeltranslation , additional fields are created in the model table with the code of all languages that are registered on the site in the LANGUAGES variable.

That is, if the usual content field and the content_markdown markdown field are added to the data model, then with the support of Russian and English languages, the following fields will be added:

  • content_ru
  • content_en
  • content_markdown_ru
  • content_markdown_en

So when a MarkdownField is named content_markdown_en it takes the value of html_field which is equal to content and adds the language code from content_markdown_en to get content_en .

This provides multilingual support for MarkdownField .

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Lissa
  • April 19, 2023, 7:57 a.m.

Большое спасибо. Очень много интересного и полезного.
p.s. Маленькая опечатка в слове "мультиязычности" (4 строка)

Comments

Only authorized users can post comments.
Please, Log in or Sign up
AD

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:20points,
  • Rating points-10
Last comments
i
innorwallNov. 14, 2024, 5:09 p.m.
Qt/C++ - Tutorial 068. Hello World using the CMAKE build system in CLion ditropan pristiq dosing With the Yankees leading, 4 3, Rivera jogged in from the bullpen to a standing ovation as he prepared for his final appearance in Chicago buy priligy pakistan
i
innorwallNov. 14, 2024, 12:05 p.m.
EVILEG-CORE. Using Google reCAPTCHA 2001; 98 29 34 priligy buy
i
innorwallNov. 14, 2024, noon
PyQt5 - Lesson 007. Works with QML QtQuick (Signals and slots) priligy 30mg Am J Obstet Gynecol 171 1488 505
i
innorwallNov. 14, 2024, 10:54 a.m.
Django - Tutorial 003. Model, Template, View on Django Hair follicles are believed to produce approximately 20 individual hair shafts over the life of the follicle as the follicle progresses through cycles of hair production, shedding ejection, invo…
i
innorwallNov. 14, 2024, 7:03 a.m.
How to make game using Qt - Lesson 3. Interaction with other objects what is priligy tablets What happens during the LASIK surgery process
Now discuss on the forum
i
innorwallNov. 14, 2024, 11:39 a.m.
добавить qlineseries в функции priligy amazon canada 93 GREB1 protein GREB1 AB011147 6
i
innorwallNov. 11, 2024, 6:55 p.m.
Всё ещё разбираюсь с кешем. priligy walgreens levitra dulcolax carbs The third ring was found to be made up of ultra relativistic electrons, which are also present in both the outer and inner rings
9
9AnonimOct. 25, 2024, 4:10 p.m.
Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…

Follow us in social networks