Evgenij LegotskojFeb. 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.


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()
                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.
- company blog
Support the author Donate


Only authorized users can post comments.
Please, Log in or Sign up
Card image cap
Pulsum Via

Project for travelers from EVILEG.


Let me recommend you a great European Fornex hosting.

Fornex has proven itself to be a stable host over the years.

For Django projects I recommend VPS hosting

Following the link you will receive a 5% discount on shared hosting services, dedicated servers, VPS and VPN

View Hosting
Share on social networks

The EVILEG project has switched to a non-commercial basis and will develop solely on the enthusiasm of the site creator, the enthusiasm of users, donations and the hosting referral system

Thank you for your support

Available ways to support the project



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

  • Result:80points,
  • Rating points4

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

  • Result:66points,
  • Rating points-1

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

  • Result:90points,
  • Rating points8
Last comments

Qt/C++ - Lesson 061. Adding images to the application using the Drag And Drop method from the file manager

Доброго времени суток. А если нужно и изображение и текст? Что-то потерялся немного.... // Вместо отрисовки иконки и текста будем отрисовывать только одно изображение // с н…

Qt/C++ - Lesson 004. QSqlTableModel – How to present the table from database?

error insert into TableExample " Количество параметров не совпадает" Я путь свой прописывала и даже бд удаляла, чтобы заново сделать, не работает. (всё остальное как у вас... Вроде ка…

Qt/C++ - Lesson 042. PopUp notification in the Gnome style using Qt

cialis powder comprare cialis online

GameDev on Qt - Tutorial 1. Track mouse movement in QGraphicsScene

Вполне возможно, что ты не закинул graphicsView в дизайнере в виджет

GameDev on Qt - Tutorial 1. Track mouse movement in QGraphicsScene

Кому интересно, поворот в slotTarget можно в одну строку организовать this->setRotation(90 + rotation() + qRadiansToDegrees(qAtan2(mapFromScene(point).y(), mapFromScene(point).x())));
Now discuss on the forum

Sorting the added QML elements in the ListModel

legal online pharmacy
  • Nomad
  • July 30, 2022, 5:42 a.m.

Как работать с HTMX?

Приветствую колеги. На днях наткнулся на вот это : https://htmx.org/ На офф сайте написанно вот такая фраза: htmx gives you access to AJAX, CSS Transitions, We…
  • harisr
  • July 25, 2022, 2:56 a.m.

QT - Native App Integration

Привет, у нас уже есть собственное приложение для Android. Можем ли мы интегрировать пользовательское представление QT в приложение со всем приложением QT внутри представления. Если да, ука…

Правильный запуск сервера на vps - Django

О я как то себе дома локальный сервер создавал. Вам же нужно просто сделать ручками конфигурацию системы. Настроить Nginx ну либо Apache (тут кому что нравится). Соответственно БД и всё остально…

Распознание объектов

Я к тому, что, возможно, софт уже есть.
© EVILEG 2015-2022
Recommend hosting TIMEWEB