【问题标题】:ForeignKey dateField result noneForeignKey dateField 结果无
【发布时间】:2018-05-20 05:02:21
【问题描述】:

这里是我的模型和视图

models.py

class ClosingDate(models.Model):
    ...
    name = models.CharField(max_length=255)
    date_from = models.DateField()

class Salary(models.Model):
    ...
    closingdate = models.ForeignKey(ClosingDate, related_name='closingdate')
    desc = models.TextField(blank=True, null=True)

Views.py

class CreateView(CreateView):
    fields = ('employee', 'closingdate')
    model = models.Salary

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.desc = str(self.object.closingdate.date_from)
        self.object.save()

        return super(ModelFormMixin, self).form_valid(form)

我试图获取 datefield 并将其发布到 str,我使用 str(self.object.closingdate.date_from) 但没有结果。但是当我尝试取名为 str(self.object.closingdate.name) 时,它也能正常工作。

我的代码有什么问题?...我该怎么办?...谢谢!

【问题讨论】:

  • 使用python日期类的strftime方法

标签: python django django-views


【解决方案1】:

你不能通过这种方式将datetime转换成字符串,你应该使用属性strftime
See the documentation

date.strftime(format)

它返回一个表示日期的字符串,由显式格式字符串控制。:

self.object.closingdate.date_from.strftime("%B %d, %Y %I:%M:%S %p")

【讨论】:

  • 收到错误'NoneType' object has no attribute 'strftime'
  • 在使用它之前,请确保self.object.closingdate.date_fromif statement 具有datetitme 值
猜你喜欢
  • 2017-10-19
  • 2020-11-20
  • 2017-03-21
  • 2020-11-22
  • 2021-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-13
相关资源
最近更新 更多