无法将datetime.now()保存到DateTimeField

时间:2015-04-14 00:48:40

标签: python django datetime python-3.x

我已经定义了一个模型如下(缩短了问题)

from datetime import datetime, date, timedelta

class Case(models.Model):
    received_email_sent = models.DateTimeField(null=True, blank=True, default=None)

    def send_received_email(self):
        message = settings.EMAIL_HEADER + self.case_received_email() + settings.EMAIL_FOOTER
        send_mail('Subject here', message, settings.EMAIL_HOST_USER, ['xxx@xxx.com'], fail_silently=False)
        self.received_email_sent = datetime.now()

在视图中我在现有对象上调用send_received_email。我知道正在输入send_received_email块,因为我每次测试时都会收到电子邮件,但self.received_email_sent = datetime.now()部分每次都将该字段保留为默认值(None)。以下是该观点的相关部分:

from logbook.models import Case

def job_email(request, case_id):
    case = get_object_or_404(Case,pk=case_id)
    case.send_received_email()
    return HttpResponseRedirect('/jobs/'+str(case.case_id))

我还尝试了另一种方法,在视图而不是模型中保存字段,如下所示:

模型:

class Case(models.Model):
    received_email_sent = models.DateTimeField(null=True, blank=True, default=None)
    def send_received_email(self):
        message = settings.EMAIL_HEADER + self.case_received_email() + settings.EMAIL_FOOTER
        send_mail('Subject here', message, settings.EMAIL_HOST_USER, ['xxx@xxx.com'], fail_silently=False)
        #self.received_email_sent = datetime.now()

的观点:

from datetime import datetime
from logbook.models import Case

def job_email(request, case_id):
    case = get_object_or_404(Case,pk=case_id)
    case.send_received_email()
    case.received_email_sent = datetime.now()
    return HttpResponseRedirect('/jobs/'+str(case.case_id))

我还尝试了上述两种路线,并进行了各种调整,例如删除现在的括号()并将from datetime import datetime更改为import datetime。没有快乐。谢谢你看看这个。

1 个答案:

答案 0 :(得分:2)

您需要在self.save()结束时致电send_received_email()