Choosing a django translation model

I need to translate the selection for the field on the model. I have something like this:

from django.utils.translation import ugettext as _ from django.db import models class MyModel(models.Model): TYPES = ( (1, _("Option one")), (2, _("Option two")) (3, _("Option three")) ) type = models.CharField(max_length=50, choices=TYPES) 

Before that, I have a script in the input view:

 request.session['django_language'] = request.POST.get("language") 

So the problem is that django calls TYPES on MyModel because request.session ['django_language'] does not exist.

Any help would be greatly appreciated.

Thanks...

+6
source share
2 answers

In models.py you need

 from django.utils.translation import ugettext_lazy as _ 

ugettext_lazy will return the called, not the translated string. When the called is evaluated later, it will return the translated string. It will be late enough for him to get the correct language for processing the view / template.

See https://docs.djangoproject.com/en/dev/topics/i18n/translation/#lazy-translations .

This next part was not your question, but: in django, you should use forms to process user input, and not access it directly with request.POST.get. This is a whole different topic, but I could not let her go unanswered in this answer, fearing that someone else might use this method.

+11
source

models.py

  CATEGORIES = ( ('LAB', 'labor'), ('CAR', 'cars'), ('TRU', 'trucks'), ('WRI', 'writing'), 

)

 class PostAd(models.Model): name = models.CharField(max_length=50) email = models.EmailField() gist = models.CharField(max_length=50) category = models.CharField(max_length=3, choices=CATEGORIES) 

forms.py

 CATEGORIES = ( ('LAB', 'labor'), ('CAR', 'cars'), ('TRU', 'trucks'), ('WRI', 'writing'), 

)

 category = forms.ChoiceField(choices=CATEGORIES, required=True ) 

category.html

  <!-- category --> <div class="fieldWrapper"> {{ form.category.errors }} <label for="id_category">Category</label> {{ form.category }} </div> <!-- location --> 
0
source

Source: https://habr.com/ru/post/958900/


All Articles