My main code is this:
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
When I run this code, I get:
'DateTimeField' object has no attribute 'strftime'
referring to publishdate
strftime works with datetime.datetime, and DateTimeField converts to datetime.datetime, so what am I doing wrong?
I've tried to convert to datetime.datetime to no avail
EDIT: Having seen answers, I think I should verify what I'm trying to do
I'm trying to add the date to this url in urls.py:
urlpatterns = [
path('', views.PostList.as_view(), name='home'),
path('<publishdate>/<slug:slug>', views.PostDetail.as_view(), name='post_detail'
]
EDIT 2: I've updated my code to this:
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
and the output is:
File "C:\Users\[user]\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 933, in value_from_object
return getattr(obj, self.attname)
AttributeError: 'DateTimeField' object has no attribute 'attname'