• 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
    

      

  • 相关阅读:
    11.10 安装GMONE3,卸载 UNITY和UNITY 2D
    Ubuntu 11.10 使用Gnome3 快捷键Alt+F2无效的解决办法
    Ioc容器应用浅析EasyJF学习
    JPA批注参考
    MVC(Model/View/Controller)EasyJF学习
    Subversion使用手記
    Eclipse 插件 esourceBundleEditor
    用 Subversion 构建版本控制环境
    TortoiseSVN使用
    自信的真正含义NLP
  • 原文地址:https://www.cnblogs.com/feifeifeisir/p/13743423.html
Copyright © 2020-2023  润新知