From ee52689c1c2102ba8e0b48f86385687fe07a2f96 Mon Sep 17 00:00:00 2001 From: Gabriel Augendre Date: Sun, 16 Aug 2020 18:15:19 +0200 Subject: [PATCH] Add mass (un)publish action --- articles/admin.py | 25 ++++++++++++++++++++++++- articles/models.py | 17 +++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/articles/admin.py b/articles/admin.py index 2402043..8e77718 100644 --- a/articles/admin.py +++ b/articles/admin.py @@ -1,4 +1,4 @@ -from django.contrib import admin +from django.contrib import admin, messages from django.contrib.admin import register from django.contrib.auth.admin import UserAdmin @@ -35,3 +35,26 @@ class ArticleAdmin(admin.ModelAdmin): ("Content", {"fields": ("content",)}), ] readonly_fields = ["created_at", "updated_at", "views_count"] + + def publish(self, request, queryset): + if not request.user.has_perm("articles.change_article"): + messages.warning(request, "You're not allowed to do this.") + return + for article in queryset: + article.publish(save=False) + Article.objects.bulk_update(queryset, ["published_at", "status"]) + messages.success(request, f"{len(queryset)} articles published.") + + publish.short_description = "Publish selected articles" + + def unpublish(self, request, queryset): + if not request.user.has_perm("articles.change_article"): + messages.warning(request, "You're not allowed to do this.") + return + for article in queryset: + article.unpublish(save=False) + Article.objects.bulk_update(queryset, ["published_at", "status"]) + messages.success(request, f"{len(queryset)} articles unpublished.") + + unpublish.short_description = "Unpublish selected articles" + actions = [publish, unpublish] diff --git a/articles/models.py b/articles/models.py index 4c466bb..3399ceb 100644 --- a/articles/models.py +++ b/articles/models.py @@ -3,6 +3,7 @@ import re import markdown from django.contrib.auth.models import AbstractUser from django.db import models +from django.utils import timezone class User(AbstractUser): @@ -28,6 +29,9 @@ class Article(models.Model): class Meta: ordering = ["-published_at"] + def __str__(self): + return self.title + def get_abstract(self): html = self.get_formatted_content() return html.split("")[0] @@ -37,3 +41,16 @@ class Article(models.Model): content = self.content content = re.sub(r"(\s)#(\w+)", r"\1\#\2", content) return md.convert(content) + + def publish(self, save=True): + if not self.published_at: + self.published_at = timezone.now() + self.status = self.PUBLISHED + if save: + self.save() + + def unpublish(self, save=True): + self.published_at = None + self.status = self.DRAFT + if save: + self.save()