我的主要代码是这样的:
class Post(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')
updated_on = models.DateTimeField(auto_now=True)
image = models.ImageField(upload_to='images/%Y/%m/%d/', blank=True)
content = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=0)
publishdate = created_on.strftime('%Y/%m')
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
当我运行这段代码时,我得到:
'DateTimeField' object has no attribute 'strftime'
参考发布日期
strftime 与 datetime.datetime 一起使用,而 DateTimeField 转换为 datetime.datetime,那么我做错了什么?
我尝试转换为 datetime.datetime 无济于事
编辑:看到答案后,我想我应该验证我想要做什么
我正在尝试将日期添加到 urls.py 中的此网址:
urlpatterns = [
path('', views.PostList.as_view(), name='home'),
path('<publishdate>/<slug:slug>', views.PostDetail.as_view(), name='post_detail'
]
编辑2:我已将代码更新为:
class Post(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')
updated_on = models.DateTimeField(auto_now=True)
image = models.ImageField(upload_to='images/%Y/%m/%d/', blank=True)
content = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=0)
created_on_string = created_on.value_to_string(created_on)
publishdate = strptime(created_on_string, '%Y/%m')
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
jeck猫
呼啦一阵风
相关分类