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
d
  • dsfs
  • April 26, 2024, 11:56 a.m.

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

  • Result:80points,
  • Rating points4
d
  • dsfs
  • April 26, 2024, 11:45 a.m.

C++ - Test 002. Constants

  • Result:50points,
  • Rating points-4
d
  • dsfs
  • April 26, 2024, 11:35 a.m.

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

  • Result:73points,
  • Rating points1
Last comments
k
kmssrFeb. 9, 2024, 2: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, 6:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 4:38 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 19, 2023, 5:01 a.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
BlinCT
BlinCTMay 5, 2024, 12:46 p.m.
Написать свой GraphsView Всем привет. В Qt есть давольно старый обьект дял работы с графиками ChartsView и есть в 6.7 новый но очень сырой и со слабым функционалом GraphsView. По этой причине я хочу написать х…
BlinCT
BlinCTMay 5, 2024, 12:44 p.m.
добавить qlineseries в функции Давно я не работал с виджетами и с формами, на мой взгляд уже пережитов, и в управлении не очень удобное это все. Н оя у вас не увидел в коде где вы QCharts растягиваете на область парента.…
PS
Peter SonMay 4, 2024, 12:57 a.m.
Best Indian Food Restaurant In Cincinnati OH Ready to embark on a gastronomic journey like no other? Join us at App india restaurant and discover why we're renowned as the Best Indian Food Restaurant In Cincinnati OH . Whether y…
Evgenii Legotckoi
Evgenii LegotckoiMay 2, 2024, 9:07 p.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Добрый день. По моему мнению - да, но то, что будет касаться вызовов к функционалу Андроида, может создать огромные трудности.
IscanderChe
IscanderCheApril 30, 2024, 11:22 a.m.
Во Flask рендер шаблона не передаётся в браузер Доброе утро! Имеется вот такой шаблон: <!doctype html><html> <head> <title>{{ title }}</title> <link rel="stylesheet" href="{{ url_…

Follow us in social networks