0
votes

i'm using django-modeltranslation to translate mo models in DRF

so i did all that says docs of django-modeltranslation and it work for model fields

but i cant get translated value of choicefield

from django.utils.translation import ugettext_lazy as _
class Product(models.Model):

PRODUCT_TYPES = (
    ('food', _('food')),
    ('wear', _('wear'))
)
name = models.CharField(verbose_name='Name', max_length=512, blank=True)
product_type = models.CharField('Type', choices=PRODUCT_TYPES, blank=True, null=True, max_length=16, default='food')

fields like product_name and other are translated by django-modeltranslation and works

but i always get food in product_type

i run makemessages and compilemessages

msgid "food"
msgstr "еда"

msgid "wear"
msgstr "одежда"

calling get_product_type_display did not work

class ProductSerializer(serializers.ModelSerializer):
    date = serializers.DateTimeField(read_only=True, format='%d.%m.%Y %H:%M')
    product_type = serializers.SerializerMethodField()

    class Meta:
        model = Product
        fields = ('phone_number', 'name', 'total_bonus', 'card_number', 'id', 'count', 'date', 'product_type',
                  'category')

    def get_product_type(self, obj):
        return obj.get_product_type_display()
2
have you create and compile translation before?ncopiy
yes i did makemessages and compilemessagesТаалай Дюшебеков
You need to call get_product_type_display() on Product instance. docsmon io
@monio update my question for youТаалай Дюшебеков

2 Answers

1
votes

Your serializer using get_FIELDNAME_display() object method:

class ProductSerializer(serializers.ModelSerializer):
    date = serializers.DateTimeField(read_only=True, format='%d.%m.%Y %H:%M')
    product_type = serializers.CharField(source='get_product_type_display', read_only=True)

    class Meta:
        model = Product
        fields = ('phone_number', 'name', 'total_bonus', 'card_number', 'id', 'count', 'date', 'product_type', 'category')
0
votes

I found a solution to this problem. Need to use: return _(obj.product_type)

from django.utils.translation import ugettext_lazy as _

class ProductSerializer(serializers.ModelSerializer):
    date = serializers.DateTimeField(read_only=True, format='%d.%m.%Y %H:%M')
    product_type = serializers.SerializerMethodField()

    class Meta:
        model = Product
        fields = ('phone_number', 'name', 'total_bonus', 'card_number', 'id', 'count', 'date', 'product_type',
                  'category')

    def get_product_type(self, obj):
        return _(obj.product_type)