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
Evgenii Legotckoi
Evgenii LegotckoiOct. 31, 2024, 6:37 p.m.
Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
A
ALO1ZEOct. 19, 2024, 1:19 p.m.
Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь МаксимовOct. 5, 2024, 12:51 p.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 4:02 p.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
k
kmssrFeb. 8, 2024, 11:43 p.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Now discuss on the forum
Evgenii Legotckoi
Evgenii LegotckoiJune 24, 2024, 8:11 p.m.
добавить qlineseries в функции Я тут. Работы оень много. Отправил его в бан.
t
tonypeachey1Nov. 15, 2024, 11:04 a.m.
google domain [url=https://google.com/]domain[/url] domain [http://www.example.com link title]
NSProject
NSProjectJune 4, 2022, 8:49 a.m.
Всё ещё разбираюсь с кешем. В следствии прочтения данной статьи. Я принял для себя решение сделать кеширование свойств менеджера модели LikeDislike. И так как установка evileg_core для меня не была возможна, ибо он писался…
9
9AnonimOct. 25, 2024, 2:10 p.m.
Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…

Follow us in social networks