Django TimeField模型无秒钟 [英] Django TimeField Model without seconds
问题描述
问候,
我试图实现一个仅由HH:MM(即16:46)格式组成的TimeField模型,我知道可以格式化一个普通的Python时间对象,但是我失去了如何使用Django来管理这个。
干杯
DateTime字段将始终存储秒;然而,您可以轻松地告诉模板,只显示小时和分钟,而时间
过滤器:
{{value | time:H:M}}
其中value是包含datetime字段的变量。
当然,您还可以使用其他技巧,例如在保存时从字段中删除秒数;在处理表单的视图中,需要对代码进行一个小的更改,以便执行以下操作:
if form。 is_valid():
instance = form.save(commit = False)
instance.nosecs = instance.nosecs.strptime(instance.nosecs.strftime(%H:%M),%H :%M)
instance.save()
(注意:这是一个丑陋的和/或
最后,您应该注意,管理员仍然会在该字段中显示秒。
不应该是一个很大的问题,因为管理员应该只能被一种可以被指示不使用该领域的那些用户使用。
如果你还要修补管理员,您仍然可以将自己的小部件分配给表单,从而让管理员使用它。当然,这意味着一项重要的额外努力。
Greetings, I am trying to implement a TimeField model which only consists of HH:MM (ie 16:46) format, I know it is possible to format a regular Python time object but I am lost about how to manage this with Django.
Cheers
DateTime fields will always store also seconds; however, you can easily tell the template to just show the hours and minute, with the time
filter:
{{ value|time:"H:M" }}
where "value" is the variable containing the datetime field.
Of course, you can also resort to other tricks, like cutting out the seconds from the field while saving; it would require just a small change to the code in the view handling the form, to do something like this:
if form.is_valid():
instance = form.save(commit=False)
instance.nosecs = instance.nosecs.strptime(instance.nosecs.strftime("%H:%M"), "%H:%M")
instance.save()
(note: this is an ugly and untested code, just to give the idea!)
Finally, you should note that the admin will still display the seconds in the field.
It should not be a big concern, though, because admin should be only used by a kind of users that can be instructed not to use that part of the field.
In case you want to patch also the admin, you can still assign your own widget to the form, and thus having the admin using it. Of course, this would mean a significant additional effort.
这篇关于Django TimeField模型无秒钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!