All Blogs Go to Heaven
Rounding Error!
Published: Aug. 15, 2019, 7:13 p.m.
Edited: Sept. 2, 2019, 11:29 p.m.
edit: updated using "mistune" and "pygments". It was difficult to find this solution, but easy to do once I found it.
To all of my loyal reader,
You may have noticed that an edited date and time was showing up even for some blog posts that happened at the same time (I only noticed it 20 minutes ago). I was confused because I thought I had already accounted for this.
Well, I had, but actually, no, I hadn't. I defined a method in the model that defines a blog post.
class BlogPost(models.Model):
is_published = models.BooleanField()
date_created = models.DateTimeField()
last_updated = models.DateTimeField()
date_published = models.DateTimeField(null=True, blank=True)
# ... stuff that doesn't matter here...
def is_edited(self):
time_diff = self.last_updated - self.date_published
# Seconds are not cumulative
return (time_diff.seconds > 2 * 60) or (time_diff.days > 0)
I spent a little time on this because I was initially confused by the fact that the seconds
attribute is not cumulative. If I update a page exactly one day later, the attribute will be zero. When I noticed the problem I was further confused by the fact that posts that I immediately published instead of saving and publishing later didn't have this issue. If I publish and save in one go, it's done a little differently than if I save and publish later. Usually when I publish later I use a button that can be customized by inheriting from the built in Django admin.ModelAdmin
.
Until about 6:15 today this was the code (skipping a few distracting lines):
class BlogPostAdmin(admin.ModelAdmin):
list_display = ['title', 'is_published', 'date_created', 'date_published']
ordering = ['date_created']
actions = ['publish']
def publish(self, request, queryset):
blogs_published = queryset.update(is_published=True, last_updated=timezone.now(), date_published=timezone.now())
msg = "1 blog published" if blogs_published == 1 else f"{blogs_published} blogs published"
self.message_user(request, msg)
I'm not sure what drove me to call timezone.now()
twice, but that turned out to be the problem. Of course this wouldn't happen if the difference in time could be negative.