A
A
Andrey Salnikov2017-05-15 15:07:19
Django
Andrey Salnikov, 2017-05-15 15:07:19

How to dynamically connect a field from a model?

You need to make a site with support for different languages. How to make text in templates is understandable. But I ran into a problem in the models.
There is a news model.

class News(models.Model):
    title = models.CharField(max_length=200, verbose_name='Заголовок')
    slug = models.SlugField(max_length=200, unique=True)
    pub_date = models.DateField(verbose_name='Дата публикации')
    intro_text = models.TextField(verbose_name='Краткий текст')
    intro_text_en = models.TextField(verbose_name='Краткий текст на английском')
    full_text = models.TextField(verbose_name='Полный текст')
    full_text_en = models.TextField(verbose_name='Полный текст на английском')
    hidden = models.BooleanField(default=False, verbose_name='Скрыт')

    def save(self, *args, **kwargs):
        self.slug = slugify(unidecode(self.title))
        super(News, self).save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse('news_page', kwargs={
            'slug': self.slug,
        })

    def __str__(self):
        return self.title

    class Meta:
        verbose_name = 'Новость'
        verbose_name_plural = 'Новости'

The question arises how to display the desired field with the selected language.
Is it possible somehow to display the field like this - {{ news['full_text' + select_lng] }}?
If not, can you suggest a better alternative?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Burnaev, 2017-05-15
@Shshzik

It is better to determine the current language at the context preparation level (in the view) and throw the desired content into the variable ...
As another option, write your own template filter, which will pass the article object and the current language .. which will display the desired content

V
Volton, 2017-05-16
@Volton

Well, there are tools for working with multilingual content.
For example: django-modeltranslation, django-parler

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question