我想在模板中格式化datetime.datetime
:
{{ script.lastrundate|date:'Y-m-d' }} {{script.lastrundate|time}}
但我发现序列化程序生成的值都是字符串,而不是原始类型。当我打印它们时它们很好;但如果我想格式化日期,我就会得到空字符串。
我的模特:
class TScript(models.Model):
id = models.AutoField(primary_key=True)
category = ForeignKey(TCategory, PROTECT, null=False, blank=False, to_field='name') # protect TScript from deletion; TScript belongs to TCategory
service = ForeignKey(TService, PROTECT, null=False, blank=False, to_field='name')
platform = ForeignKey(TPlatform, PROTECT, null=False, blank=False, to_field='name')
command = models.CharField(max_length=1024, blank=False, null=False)
machine = models.CharField(max_length=64, blank=False, null=False)
username = models.CharField(max_length=150, blank=False, null=False) # now save as string to avoid problem
interval = models.IntegerField(blank=False, null=False) # seconds
timeout = models.IntegerField(blank=False, null=False) # seconds
status = models.IntegerField(blank=False, null=False)
out = models.CharField(max_length=1024, blank=True, null=True)
error = models.CharField(max_length=512, blank=True, null=True)
description = models.CharField(max_length=256, blank=True, null=True)
lastrundate = models.DateTimeField(null=True)
insertDate = models.DateTimeField(auto_now_add=True)
我的序列化器:
class TScriptSerializer(serializers.ModelSerializer):
lastrundate = serializers.DateTimeField() # I changed here but not working
class Meta:
model = TScript
fields = ['id', 'category', 'service', 'platform',
'command', 'machine', 'username', 'interval',
'out', 'error', 'timeout', 'status', 'description',
'lastrundate', 'insertDate']
我的观点方法:
@login_required
@csrf_protect
def scriptsList(request):
logger.info("SCRIPTSLIST Start HTML")
try:
scripts=operationsDB.getScripts()
return render(request, 'tablescripts.html', {"scripts":scripts})
except Exception as e:
tb = traceback.format_exc(1)
logger.error('ERROR Exception in scriptsList, the error is: ' + repr(e) + " - args - " + repr(tb))
errorMsg="Exception "+repr(e)
result={"CausesError":errorMsg}
return redirect('/scriptsList/?' + urllib.urlencode(result))
operationsDB.getScripts()
:
def getScripts():
arrScripts=[]
try:
scripts=TScript.objects.all()
for script in scripts:
serializedScript=TScriptSerializer(script)
dataScript=serializedScript.data
arrScripts.append(dataScript)
return scripts
except Exception as e:
tb = traceback.format_exc(1)
logger.error('ERROR Exception in getScripts; the error is: ' + repr(e) + " - args - " + repr(tb))
return []
return arrScripts
我不明白。
编辑:此错误是关于另一个格式错误的字段,因此不相关。
错误是:
[12/Mar/2018 17:18:42] ERROR [scriptsList] - ERROR Exception in scriptsList, the error is: TypeError('argument must be 9-item sequence, not datetime.datetime',) - args - 'Traceback (most recent call last):\n File "/var/www/html/ElasticSearch/frontEnd/views.py", line 876, in scriptsList\n return render(request, \'tablescripts.html\', {"scripts":scripts})\nTypeError: argument must be 9-item sequence, not datetime.datetime\n'