views:

13

answers:

1

So, I have a form:

class FormBasicInfo(BasicForm):
    valid_from = forms.DateField(required=False, input_formats=('%d/%m/%Y',), widget=DateInput(format='%d/%m/%Y'))

and I set the input and output formats. However, what if I want to set these formats at runtime, based on the date format preference of my user? how can that be done?

The way it is done above, the form will always validate against the European date format. Even if I specify more formats which is allowed, one of them will be first and take priority which means there will be cases when the validation will be done incorrectly.

+1  A: 

You can override the __init__ method of the form class to customize the input_formats and widget. For e.g.

class FormBasicInfo(BasicForm):
    ....

    def __init__(self, *args, **kwargs):
        super(MForm, self).__init__(*args, **kwargs)
        valid_from = self.fields['valid_from']
        format = look_up_format_based_on_locale()
        valid_from.input_formats = (format,)
        valid_from.widget = forms.DateInput(format=format)

Where look_up_format_based_on_locale() is an abstraction for looking up the date format based on the user's locale. It should return an appropriate format string, say "%m/%d/%Y".

Manoj Govindan