Created
August 14, 2023 16:33
-
-
Save cnk/e708bfe101cc06121ba638aec2751ba9 to your computer and use it in GitHub Desktop.
Publication date field
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class NewsPage(Page): | |
... | |
publication_date = models.DateTimeField( | |
blank=True, | |
null=True, | |
help_text="This field will be automatically filled in once this news article is published. " | |
"After that, you may edit it. This date is used to sort articles and is displayed on the teaser." | |
) | |
exclude_fields_in_copy = [ | |
'go_live_at', 'expire_at', 'expired', 'publication_date' | |
] | |
class NewsPageForm(WagtailAdminPageForm): | |
def clean(self): | |
cleaned_data = super().clean() | |
# Don't let users remove the publication_date from a live article. Unfortunately, the field 'live' defaults | |
# to True for a never saved article. But having a live_revision_id appears to be an accurate indicator. | |
# This is absolutely required because our code relies on publication_date existing in order to sort News. | |
if self.instance.live_revision_id and not cleaned_data.get('publication_date'): | |
self.add_error( | |
'publication_date', | |
ValidationError('You may not remove the publication date from a live news article.') | |
return cleaned_data | |
----- | |
# signals.py | |
@receiver(page_published) | |
def update_publication_date(sender, instance, **kwargs): | |
""" | |
We need an editable 'date this was first published'. We had been using first_published_at but edits | |
get lost if someone changes first_published_at and then saves as draft. So make a new field to use for | |
display on the teaser and the article itself (and to use for sorting articles). Fill it in here. | |
""" | |
if issubclass(sender, NewsPage) or issubclass(sender, SiteNewsPage): | |
if instance.live and not instance.publication_date: | |
instance.publication_date = timezone.now() | |
instance.save(update_fields=['publication_date']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment