1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
| from django.contrib import admin from django.utils.html import format_html from django.urls import reverse from .models import Post, Category, Tag, Comment
@admin.register(Post) class PostAdmin(admin.ModelAdmin): list_display = [ "title", "author", "category", "status", "view_count", "is_featured", "published_at", ] list_display_links = ["title"] list_editable = ["status", "is_featured"] list_filter = ["status", "is_featured", "category", "created_at"] search_fields = ["title", "content", "author__username"] prepopulated_fields = {"slug": ("title",)} raw_id_fields = ["author"] date_hierarchy = "published_at" ordering = ["-published_at"] readonly_fields = ["view_count", "created_at", "updated_at"] save_on_top = True list_per_page = 25 actions = ["make_published", "make_draft", "mark_featured"]
fieldsets = ( ("基本信息", { "fields": ("title", "slug", "author", "status", "is_featured"), }), ("内容", { "fields": ("content", "summary", "featured_image"), "classes": ("wide",), }), ("分类与标签", { "fields": ("category", "tags"), }), ("统计信息", { "fields": ("view_count", "published_at", "created_at", "updated_at"), "classes": ("collapse",), }), )
filter_horizontal = ["tags"]
@admin.action(description="标记为已发布") def make_published(self, request, queryset): from django.utils import timezone updated = queryset.filter(status=Post.Status.DRAFT).update( status=Post.Status.PUBLISHED, published_at=timezone.now() ) self.message_user(request, f"成功发布 {updated} 篇文章")
@admin.action(description="标记为草稿") def make_draft(self, request, queryset): updated = queryset.update(status=Post.Status.DRAFT) self.message_user(request, f"成功将 {updated} 篇文章设为草稿")
@admin.action(description="标记为精选") def mark_featured(self, request, queryset): updated = queryset.update(is_featured=True) self.message_user(request, f"成功将 {updated} 篇文章设为精选")
@admin.register(Category) class CategoryAdmin(admin.ModelAdmin): list_display = ["name", "slug", "parent", "order", "post_count"] prepopulated_fields = {"slug": ("name",)} ordering = ["order", "name"]
def post_count(self, obj): return obj.posts.count() post_count.short_description = "文章数"
@admin.register(Comment) class CommentAdmin(admin.ModelAdmin): list_display = ["author", "post", "content_preview", "is_approved", "created_at"] list_editable = ["is_approved"] list_filter = ["is_approved", "created_at"] search_fields = ["content", "author__username"] actions = ["approve_comments"]
def content_preview(self, obj): return obj.content[:50] + "..." if len(obj.content) > 50 else obj.content content_preview.short_description = "评论内容"
@admin.action(description="审核通过") def approve_comments(self, request, queryset): updated = queryset.update(is_approved=True) self.message_user(request, f"成功审核 {updated} 条评论")
|