Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django translate model choices

I need translate a choices for a 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 this I have a script on the login view:

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

So, the problem is when django calls the TYPES on MyModel, because the request.session['django_language'] doesn't exist.

like image 207
Jon... Avatar asked Nov 27 '13 03:11

Jon...


People also ask

What is AutoField in Django?

According to documentation, An AutoField is an IntegerField that automatically increments according to available IDs. One usually won't need to use this directly because a primary key field will automatically be added to your model if you don't specify otherwise.

How do I translate text in Django?

Use the function django. utils. translation. gettext_noop() to mark a string as a translation string without translating it.

What is Max_length in Django?

The maximum length (in characters) of the field. The max_length is enforced at the database level and in Django's validation using MaxLengthValidator.

What is Related_name in Django?

The related_name attribute specifies the name of the reverse relation from the User model back to your model. If you don't specify a related_name, Django automatically creates one using the name of your model with the suffix _set. Syntax: field_name = models.Field(related_name="name")


Video Answer


3 Answers

I think I'm late to the party but I've just resolved a similar problem. There's a very good solution in the django documentation.

from django.utils.translation import gettext_lazy as _
class Student(models.Model):
    class YearInSchool(models.TextChoices):
        FRESHMAN = 'FR', _('Freshman')
        SOPHOMORE = 'SO', _('Sophomore')
        JUNIOR = 'JR', _('Junior')
        SENIOR = 'SR', _('Senior')
        GRADUATE = 'GR', _('Graduate')

    year_in_school = models.CharField(max_length=2, choices=YearInSchool.choices, default=YearInSchool.FRESHMAN,)

SEE LINK

Alternatively.

  1. Deploy enums (enums.py) within the app folder like so:

.

from enum import Enum, unique
from django.utils.translation import gettext_lazy as _
@unique class SomeChoice(Enum):
  first = _('First Option')
  second = _('Second Option')

Obviously, you'll then import the enum into your model & use as needed. e.g

name = models.CharField(max_length=30, db_index=True, choices=[(s.name, s.value) for s in SomeChoice])

At this stage, I'm assuming you've already written your locale files, so you have your .po files already set up.

#Append your translation content within .po | or via rosetta app

django-admin makemessages -all

django-admin compilemessages

Click the alternative language link

like image 50
Magere Avatar answered Oct 25 '22 23:10

Magere


In models.py, you need to

from django.utils.translation import ugettext_lazy as _

ugettext_lazy will return a callable rather than the translated string. When the callable is evaluated later, it will return the translated string. It will be late enough that it will get the right language for the view/template processing.

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 the user input, rather than accessing it directly from request.POST.get. That's a whole other topic, but I could not let it go unaddressed in this answer, for fear someone else might use that method.

like image 35
Brenda J. Butler Avatar answered Oct 25 '22 23:10

Brenda J. Butler


Here is an example for translating values that you save in your db.

#models.py

from django.db import models
from django.utils.translation import gettext_noop


CATEGORY_CHOICE = (
  ("choice one", gettext_noop("choice one")) # gettext_noop will mark the string to be translated when you later do "python3 manage.py makemessages"
  ("choice two", gettext_noop("choice two"))
)

class Foo(models.Model)
  category = models.CharField(choices=CATEGORY_CHOICES, max_length=50)

Just do python3 manage.py makemessages to generate the locale django.po files, enter the translations. And then do, python3 manage.py compilemessages to compile your locale files.

Now, at the time of returning this field from your views or api, just make sure to do this:

#views.py

from django.utils.translation import ugettext as _

def get_category():
  foo = Foo.objects.get(id=1)
  return _(foo.category)
like image 21
Ash Singh Avatar answered Oct 25 '22 23:10

Ash Singh