简体   繁体   English

request.POST ['time']必须为datefield()

[英]request.POST['time'] must be a datefield()

I'm very new to django, maybe I'm asking something very elemental. 我是django的新手,也许我要问的是非常基本的东西。

I have the following code : 我有以下代码:

crush.time = request.POST['time']

this 'time' post value is a timefield and I need to process as a time value, but all I got is that crush.time is a string, and then I got the following error when I try to process: 这个“时间”后的值是一个时域,我需要将其作为时间值进行处理,但是我所得到的只是rush.time是一个字符串,然后在尝试处理时出现以下错误:

'unicode' object has no attribute 'hour'

The POST multidictionary contains strings - it does not know about python data types. POST多字典包含字符串-它不了解python数据类型。 You have to parse it into a datetime object. 您必须将其解析为datetime对象。 look at the datetime documentation. 查看日期时间文档。

Assuming your ' time ' field is in the form H:M:S or H:M, then you could create a django form to do the parsing work for you (keep in mind you don't necessarily need to output the form): 假设“ 时间 ”字段的格式为H:M:S或H:M,则可以创建Django表单来为您执行解析工作(请记住,您不一定需要输出该表单):

In your forms.py: 在您的forms.py中:

from django import forms

class BasicTimeForm(forms.Form):
    time = forms.TimeField()

In your view: 您认为:

if request.method == 'POST': 
    form = forms.BasicTimeForm(request.POST)
    if form.is_valid():
        crush.time = form.cleaned_data['time']

After a post, crush.time should now contain a datetime.time. 发布后, 美眉 。时间现在应该包含一个日期时间。

(adapted from http://docs.djangoproject.com/en/dev/topics/forms/ ) (改编自http://docs.djangoproject.com/en/dev/topics/forms/

只需使用Python datetime库将其转换为时间对象即可:

datetime.datetime.strptime(request.POST['time'], '%H:%M:%S').time()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM