[英]Error AttributeError: 'str' object has no attribute 'year' when querying a model
I get startdate and enddate, but they are passed as a string.我得到 startdate 和 enddate,但它们是作为字符串传递的。 How do I convert them to a date?
如何将它们转换为日期?
startdate = request.POST["startdate"]
enddate = request.POST["enddate"]
queryset = paidparking.objects.all()
qsstats = QuerySetStats(queryset, date_field='expirationdate')
values = qsstats.time_series(startdate, enddate, interval='days')
return render(request, 'index/template.html', {'values': values})
Error in: values = qsstats.time_series(startdate, enddate, interval='days')错误:值 = qsstats.time_series(startdate, enddate, interval='days')
startdate
and enddate
are strings , not datetime
objects. startdate
和enddate
是字符串,而不是datetime
对象。 You need to parse these, so something like:你需要解析这些,所以像:
from datetime import datetime
startdate =
datetime.strptime(request.POST['startdate']
, '%Y-%m-%d')
enddate =
datetime.strptime(request.POST['enddate']
, '%Y-%m-%d')
queryset = paidparking.objects.all()
qsstats = QuerySetStats(queryset, date_field='expirationdate')
values = qsstats.time_series(startdate, enddate, interval='days')
return render(request, 'index/template.html', {'values': values})
The format here ( '%Y-%m-%d'
) might be different, depending on how the date is formatted as string.此处的格式 (
'%Y-%m-%d'
) 可能会有所不同,具体取决于日期格式为字符串的方式。
I would however advise to work with a Form
[Djang-doc] .但是,我建议使用
Form
[Djang-doc] 。 These forms make it convenient to parse, clean and validate input.这些 forms 可以方便地解析、清理和验证输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.