Enable default Django localization

We are talking about the function Localization format , which was implemented in Django 1.2.

To use this function, you must add the localize=True parameter to all fields of the form. I am trying to implement this localization in my application, but the problem is that I dynamically create my forms using the inlineformset_factory method that Django provides, so I cannot just add a new parameter to the form field.

Therefore, I tried to enable this feature by default in all models, without adding a new parameter for all fields. I created a subclass of BaseInlineFormSet and hardcoded the parameter in it.

 class MyBaseInlineFormSet(BaseInlineFormSet): def __init__(self, *args, **kwargs): super(MyBaseInlineFormSet, self).__init__(*args, **kwargs) for form in self.forms: for key, field in form.fields.iteritems(): if field.__class__ == forms.DecimalField: form.fields[key].localize = True 

This worked for only 50%. When submitting a form, Django is now correctly validated (it accepts commas, not just a period), but the fields are still not displayed correctly.

I think I could javascript get out of this problem, but I prefer to avoid this.

Any ideas on how to solve this?

+4
source share
2 answers

Django 1.2 is now 3 years old. Django 1.6 provides a great way to solve your dilemma:

From docs :

By default, fields in ModelForm will not localize their data. To enable localization for fields, you can use the localized_fields attribute in the Meta class.

 >>> from django.forms import ModelForm >>> from myapp.models import Author >>> class AuthorForm(ModelForm): ... class Meta: ... model = Author ... localized_fields = ('birth_date',) 

If localized_fields is set to the special value __all__ , all fields will be localized

+6
source

I haven't used it - (not yet for the picka project for development in Django) - but this is the case with the subclass -

Instead of inheriting your fields from forms.DecimalField, do them:

 class LocalizedDecimalField(forms.DecimalField): localize = True 
0
source

All Articles