Django表单格式选择字段时间值为AM/PM

2024-06-16 12:31:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Django表单选择字段,其中有15分钟的时隙选项:

<select id="mytime" name="mytime">
<option value="2:00 PM">2:00 PM</option>
<option value="2:15 PM">2:15 PM</option>
<option value="2:30 PM">2:30 PM</option>
<option value="2:45 PM">2:45 PM</option>
...

我的问题是,当我编辑实例值时,除非我有24小时格式的选项值,比如<option value="14:45:00">14:45:00</option>,否则不会自动选择当前时间值,因为这是匹配的数据库格式。在

视图.py

^{pr2}$

表单.py

self.fields['mytime'] = forms.ChoiceField(
                        required=True,
                        choices=options,
                        widget=forms.Select(
                            attrs={'class': 'myclass',}
                       ))

由于这是一个Select字段,小部件将不接受format属性。在

有办法吗?在

如何在我的下拉菜单中使用当前值实现AM/PM格式?在


工作代码:

在表单.py在

def __init__(self, *args, **kwargs):
options = kwargs.pop('options', None)
super(MyForm, self).__init__(*args, **kwargs)

self.fields['mytime'] = forms.ChoiceField(
                        required=True,
                        choices=options,
                        widget=forms.Select(
                            attrs={'class': 'myclass',}
                       ))

在视图.py在

 form = MyForm(request.POST or None, instance=instance,
                   options=[( choice.strftime("%H:%M:%S"), choice.strftime("%I:%M %p").lstrip('0') ) for choice in times])

Tags: pyself视图表单value格式选项forms
2条回答

如果我没弄错的话,如果标记是这样的话,一切都会成功的

<option value="14:00:00">2:00 PM</option>

你可以改变视图.py以便它生成choices元组,该元组的值为24小时格式,显示字符串为a.m.和p.m

^{pr2}$

这可以通过传递参数^{}来实现。在

类似于以下内容的东西应该可以做到这一点

if instance:
    mytime_initial = time.strptime(instance.mytime, '%I:%M %p').lstrip('0')
else:
    mytime_initial = None

self.fields['mytime'] = forms.ChoiceField(
    required=True,
    choices=options,
    initial=mytime_initial,
    widget=forms.Select(
        attrs={'class': 'myclass',}
    )
)

相关问题 更多 >