【问题标题】:Django Forms - Format Select Field Time Value as AM/PMDjango 表单 - 格式选择字段时间值作为 AM/PM
【发布时间】:2015-04-20 15:26:09
【问题描述】:

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

<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 小时格式的选项值,例如 &lt;option value="14:45:00"&gt;14:45:00&lt;/option&gt;,因为那是匹配的数据库格式。

views.py

times = []
for i in range(0, 24*4):
    times.append((datetime.combine(date.today(), time()) + timedelta(minutes=15) * i).time().strftime("%I:%M %p").lstrip('0'))
form = MyForm(instance=instance, 
       options=[( choice, choice ) for choice in times])
return ...

forms.py

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

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

有什么办法吗?

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


工作代码:

forms.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',}
                       ))

view.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])

【问题讨论】:

    标签: python django


    【解决方案1】:

    如果我理解正确,如果标记看起来像这样,一切都会正常

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

    您可以更改 views.py 使其生成具有 24 小时格式值的 choices 元组和带有上午和下午的显示字符串

    times = []
    for i in range(0, 24*4):
        times.append((datetime.combine(date.today(), time()) + timedelta(minutes=15) * i).time())
    form = MyForm(instance=instance,
           options=[( choice.strftime("%H:%M:%S"), choice.strftime("%I:%M %p").lstrip('0') ) for choice in times])
    return ...
    

    【讨论】:

    • 所以,毕竟,错误是由其他解决方案中的一段代码触发的,并且一切正常!再次感谢您的宝贵时间和宝贵的反馈!非常感谢!
    【解决方案2】:

    这可以通过传递参数initial来实现。

    类似下面的东西应该可以解决问题

    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',}
        )
    )
    

    【讨论】:

    • 感谢您的反馈。您的解决方案让我走上了正轨,一旦我将mytime_initial 转换为字符串,我就得到了一个工作代码。话虽如此,我仍在尝试使用@sthzg 解决方案,因为它可能需要更少的表单代码。无论哪种方式,再次感谢您的时间和反馈!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-20
    • 2020-05-23
    • 1970-01-01
    • 2021-02-17
    • 2013-04-11
    • 1970-01-01
    相关资源
    最近更新 更多