异常值:strTime()参数1必须是str,而不是Non

2024-04-27 05:13:44 发布

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

我正在尝试从我的django应用程序获取用户输入(DateField),此代码将给出上述错误

错误代码:

def home(request):
today = datetime.date.today()
# If this is a POST request then process the Form data
if request.method == 'GET':

    form = DeadlineForm(request.GET)
    # instance = form.save()
    currentdate = datetime.date.today()
    print(currentdate)
    userinput = formd.data
    birthday = datetime.datetime.strptime(userinput,    '%m/%d/%Y').date()
    # print(birthday)
    days = birthday - currentdate
    daysLeft = 'Days to your birthday is ' ,+ days 
    return HttpResponse(daysLeft)
context = {
    'form': form,
    'today':today
}
return render(request, 'calculator/home.html', context)

但当我使用字符串日期格式时,一切正常,但我希望用户能够插入他们自己的日期。在

无误代码:

^{pr2}$

请有人告诉我如何从用户那里获得字符串输入。在


Tags: 代码用户formhomedatagettodaydatetime
3条回答

以下是strptime()方法-

time.strptime(string[, format])

下面的示例显示strptime()方法的用法。在

^{pr2}$

当我们运行上述程序时,会产生以下结果–

返回的元组:(2000,11,30,0,0,0,3,335,-1)

试试这个

def home(request):
   today = datetime.date.today()
   # If this is a POST request then process the Form data
   if request.method == 'POST':

       form = DeadlineForm(request.POST)
       # instance = form.save()
       currentdate = datetime.date.today()

       userinput = form.cleaned_data['date']
       or
       userinput = request.POST.get('date')

       birthday = datetime.datetime.strptime(userinput,    '%m/%d/%Y').date()
       # print(birthday)
       .....

在userinput中,您没有向strptime函数传递任何值

并使用post方法从表单中获取用户输入

因此,首先,您是在错误的方法下处理表单输入

GET负责呈现表单,在那个时候用户并没有提供任何数据,这就是为什么没有提供任何数据

伪代码:

if request.method == 'GET':
  render_form
if request.method == 'POST':
  handle_form

相关问题 更多 >