How to change DECIMAL_SEPARATOR and THOUSAND_SEPARATOR used in serializers as part of django rest?

How can I change DECIMAL_SEPARATOR and THOUSAND_SEPARATOR used to serialize DecimalField? Or how can I make django-rest-framework automatically use the correct ones depending on l10n?

My situation:

I am using the django rest framework ModelSerializer to serialize a model like the following:

class House(models.Model):
    name = models.CharField(max_length=200)
    area = models.DecimalField(max_digits=7, decimal_places=2)

The serializer.py code is as follows:

class HouseSerializer(serializers.ModelSerializer):
    class Meta:
        model = House

And in settings.py, I set the localization parameters correctly, which work fine in templates:

LANGUAGE_CODE = 'en-us'
USE_I18N = True
USE_L10N = True
LANGUAGES = (
    ('es', _('Spanish')),
    ('en', _('English')),
)

USE_THOUSAND_SEPARATOR = True

LOCALE_PATHS = (
    os.path.join(BASE_DIR, 'locale'),
)

I am using ModelViewSet:

class HouseViewSet(viewsets.ModelViewSet):
    serializer_class = serializers.HouseSerializer
    queryset = House.objects.all()

And finally, I have urls.py with the i18n part in the URL:

router = DefaultRouter()
router.register(r'house', viewsets.HouseViewSet)

urlpatterns += i18n_patterns('',
    url(r'^api/', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
)

When I request data (GET) in example.com/ en / api / house /, I get the correct decimal field formation:

{
    "name": "House in L.A.", 
    "area": "1,234.50", 
} 

, (GET) example.com/ es/api/house/, , . :

{
    "name": "Casa en L.A.", 
    "area": "1.234,50", 
} 

? !

+4
2

, DRF . Django ( ):

DRF.

django django.utils.format - number_format. .

:

from django.utils.formats import number_format


class HouseSerializer(serializers.ModelSerializer):
    area = serializers.SerializerMethodField('area_localize')

    class Meta:
        model = House

    def area_localize(self, obj):
        return number_format(obj.area)
+1

, null = True ( ), , area = null. , .

:

class House(models.Model):
    name = models.CharField(max_length=200)
    area = models.DecimalField(max_digits=7, decimal_places=2, blank=True, null=True)

, , :

from django.utils.formats import number_format

class HouseSerializer(serializers.ModelSerializer):
    area = serializers.SerializerMethodField('area_localize')

    class Meta:
        model = House

    def area_localize(self, obj):
        if obj.area:
            return number_format(obj.area)
        else: 
            return None
0

All Articles