django后台中如何在result_list内优雅的显示及使用过滤器?

admin.py

from django.contrib import admin
from django.utils.safestring import mark_safe
from .models import BlogArticle


class BlogArticleAdmin(admin.ModelAdmin):
    list_display = ('title', 'show_author', 'created_time', 'updated_time')
    list_filter = ('created_time', 'author', 'updated_time')
    search_fields = ('title', 'body')
    date_hierarchy = 'created_time'
    ordering = ['author']
    readonly_fields = ('author', 'created_time', 'updated_time')

    def show_author(self, obj):
        return mark_safe('<a href="?author__id__exact={}">{}</a>'.format(
            obj.author.pk,
            obj.author.username
        ))

    def get_queryset(self, request):
        qs = super(BlogArticleAdmin, self).get_queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(author=request.user)

    def get_readonly_fields(self, request, obj=None):
        """  重新定义此函数,限制普通用户所能修改的字段  """
        if request.user.is_superuser:
            self.readonly_fields = []
        return self.readonly_fields

    def save_model(self, request, obj, form, change):
        if getattr(obj, 'author', None) is None:
            obj.author = request.user
        super().save_model(request, obj, form, change)


admin.site.register(BlogArticle, BlogArticleAdmin)

  

models.py

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User


class BlogArticle(models.Model):
    title = models.CharField('标题', max_length=300)
    author = models.ForeignKey(User, models.PROTECT, verbose_name='作者', related_name="blog_posts")
    body = models.TextField('文章内容')
    created_time = models.DateTimeField('创建于', default=timezone.now)
    updated_time = models.DateTimeField('编辑于', auto_now=True)
    is_delete = models.BooleanField('是否删除', default=False)

    class Meta:
        ordering = ("-created_time",)

    def __str__(self):
        return self.title

  

posted @ 2020-09-28 10:23  傻白甜++  阅读(474)  评论(0编辑  收藏  举报
TOP