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
МВ

Qt - Test 001. Signals and slots

  • Result:68points,
  • Rating points-1
ЛС

C++ - Test 001. The first program and data types

  • Result:53points,
  • Rating points-4
АА

C++ - Test 001. The first program and data types

  • Result:60points,
  • Rating points-1
Last comments
ИМ
Игорь МаксимовOct. 5, 2024, 5:51 p.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 9:02 p.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
k
kmssrFeb. 9, 2024, 5:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 9:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
Now discuss on the forum
K
KeithfapOct. 13, 2024, 7:24 p.m.
добавить qlineseries в функции North Symbol by Bubnov Ltd https://seven-elephants.com/en/categories/penthouse/ Искеле – жемчужина острова! Все факторы говорят про большой инвестиционный потенциал данного района как для …
JW
Jhon WickOct. 2, 2024, 1:52 a.m.
Indian Food Restaurant In Columbus OH| Layla’s Kitchen Indian Restaurant If you're looking for a truly authentic https://www.laylaskitchenrestaurantohio.com/ , Layla’s Kitchen Indian Restaurant is your go-to destination. Located at 6152 Cleveland Ave, Colu…
КГ
Кирилл ГусаревSept. 27, 2024, 7:09 p.m.
Не запускается программа на Qt: точка входа в процедуру не найдена в библиотеке DLL Написал программу на C++ Qt в Qt Creator, сбилдил Release с помощью MinGW 64-bit, бинарнику напихал dll-ки с помощью windeployqt.exe. При попытке запуска моей сбилженной программы выдаёт три оши…
F
FynjyJuly 22, 2024, 2:15 p.m.
при создании qml проекта Kits есть но недоступны для выбора Поставил Qt Creator 11.0.2. Qt 6.4.3 При создании проекта Qml не могу выбрать Kits, они все недоступны, хотя настроены и при создании обычного Qt Widget приложения их можно выбрать. В чем может …

Follow us in social networks