Search code examples
djangolocalizationfloating-pointdjango-forms

Localization of Django model float field in forms


I'm trying to localize a model float field in django forms.

This way it's working:

super(....)
self.fields["field_name"] = forms.FloatField(localize=True)

However I don't want to define a new form field, instead I would like to add the localization to my existing model field. This way it isn't working:

super(....)
self.fields['field_name'].localize = True

Does anyone know where I'm going wrong with my approach?

Thanks, Jonas


Solution

  • The issue is that the form field does various bits of initialization when it is instantiated, and setting the localize attribute after that does not rerun that initialization. See the code.

    You might be able to get most of what you want by additionally setting the is_localized attribute on the widget:

    self.fields['field_name'].localize = True
    self.fields['field_name'].widget.is_localized = True
    

    but at this point you'd probably be better off re-declaring the field anyway.