[Fixed]-Make Django forms use comma as decimal separator

21πŸ‘

βœ…

Yes, localization does need to be turned on explicitly for every field. For a model form (including the ones used in the admin app), a convenient way to do this is to subclass ModelForm and turn on localization for each DecimalField:

import django

class LocalizedModelForm(django.forms.ModelForm):
    def __new__(cls, *args, **kwargs):
        new_class = super(LocalizedModelForm, cls).__new__(cls, *args, **kwargs)
        for field in new_class.base_fields.values():
            if isinstance(field, django.forms.DecimalField):
                field.localize = True
                field.widget.is_localized = True
        return new_class

Then you can define your custom ModelForm class and use it in the admin app:

class FooForm(LocalizedModelForm):

    class Meta:
        model = Foo


django.admin.site.register(Foo, form=FooForm)
πŸ‘€Vebjorn Ljosa

10πŸ‘

In django >= 1.6 there is a simple solution to this:

from django.forms import ModelForm

class YourModelForm(ModelForm):
    class Meta:
        model = YourModel
        localized_fields = '__all__'

django.admin.site.register(YourModel, form=YourModelForm)

See the official documentation for a more verbose explanation.

πŸ‘€zvyn

8πŸ‘

Right, this looks like an annoying breakage that I’m surprised no-one has reported. Because of the change you mention, localization has to be explicitly turned on for every field in your admin app or model form. The best way to do this would be to define a custom ModelForm for use both in the admin and in your app, and set the widgets dictionary to enable localization on each relevant field.

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel
        widgets = {
            'my_decimal_field': forms.TextInput(attrs={'localization': True}),
        }

Leave a comment