开发者

django form datefield with runtime formatting

开发者 https://www.devze.com 2023-01-19 11:40 出处:网络
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\'))

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 abo开发者_开发问答ve, 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.


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".

0

精彩评论

暂无评论...
验证码 换一张
取 消