Reputation: 302
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
Upvotes: 2
Views: 2445
Reputation: 111
Django provides a way to tell explicitly which fields should be localized. You just add 'localized_fields' to your Meta Model class.
class FormEditBuilding(forms.ModelForm):
class Meta:
model = Building
exclude = []
localized_fields = ['apartments_sqm', 'offices_sqm']
Django-Docs: https://docs.djangoproject.com/en/5.0/topics/forms/modelforms/#enabling-localization-of-fields
Thanks to @heyhugo
Upvotes: 0
Reputation: 11
My approach was:
settings.py
DECIMAL_SEPARATOR = ','
USE_THOUSAND_SEPARATOR = True
Form's __init__ function
def __init__(self, *args, **kwargs):
super(YourForm, self).__init__(*args, **kwargs)
self.fields['field'].localize = True
self.fields['field'].widget.is_localized = True
Upvotes: 1
Reputation: 599580
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.
Upvotes: 3