django openpyxl 为空时的日期字段错误
我想导入 excel 工作表,但日期字段为空。
class Drgmt(models.Model):
date_ori = models.DateTimeField(default=None, null=True, blank=True)
def import(request):
#Many lines before
date_ori = dt.datetime.strftime(parse(row_data[19]), '%Y-%m-%d %H:%M:%S')
#Many lines after
回溯(最近一次调用(:
File "C:UsersAppDataRoamingPythonPython37site-packagesdjangocorehandlersexception.py", l
ine 34, in inner
response = get_response(request)
File "C:UsersAppDataRoamingPythonPython37site-packagesdjangocorehandlersbase.py", line 1
15, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:UsersAppDataRoamingPythonPython37site-packagesdjangocorehandlersbase.py", line 1
13, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:UsersDesktopperformancecuivreviews.py", line 57, in importeradsl date_ori = dt.datetime.strftime(parse(row_data[19]), '%Y-%m-%d %H:%M:%S')
File "C:UsersAppDataLocalContinuumanaconda3libsite-packagesdateutilparser_parser.py", li
ne 1356, in parse
return DEFAULTPARSER.parse(timestr, **kwargs)
File "C:UsersAppDataLocalContinuumanaconda3libsite-packagesdateutilparser_parser.py", li
ne 648, in parse
raise ValueError("Unknown string format:", timestr)
ValueError: ('Unknown string format:', 'None')
[18/Jun/2019 08:37:02] "POST /cuivre/ HTTP/1.1" 500 85133
好吧,错误消息相当清楚:您将字符串'None'
作为dateutil.parser.parse()
的timestr
参数传递,而解析器显然无法将其解析为日期。
解决方案也很明显:处理异常:
def import(request):
#Many lines before
try:
date_ori = parse(row_data[19])
except ValueError as e:
# what you want to do here depends on your app's specs and rules...
# you could return an error response, or skip the row and
# just display a warning, etc etc
do_something_with_the_exception_here()
else:
date_ori = dt.datetime.strftime(date_ori, '%Y-%m-%d %H:%M:%S')
#Many lines after