Django Admin Site

1. 自定后台管理面板列表显示的返回值

class ThesisTopicReviewHistoryAdmin(admin.ModelAdmin):
list_display = ('reviewer', 'thesisTopic', 'comment', 'state', )
list_filter = ('state', 'reviewer', 'created', )
search_fields = ('thesisTopic',)

def save_model(self, request, obj, form, change):
    # 保存该评审记录
    obj.save()
    # 改变相应题目的评审状态
    topic = obj.thesisTopic
    topic.reviewState = obj.state
    topic.save()

def get_readonly_fields(self, request, obj=None):
    if request.user.is_superuser:
        return ()
    else:
        return self.list_display

以上类如get_attrbute_fields()的方法均可以重写。
如果需要让一个timestamp类型的create_at属性不是显示整数二十显示一个完整的日期,可以重写此方法.

class TeacherReviewAdmin(admin.ModelAdmin):
list_display = ('get_topic', 'student', 'comment', 'score','create_at','get_year', 'review_state',)
list_filter = ('student__year', 'student__studentClass', 'student__studentClass__campus')
search_fields = ('student__name', 'student__studentNo')
teacher_readonly_fields = ('student', 'topic', 'finalthesisdoc',)
teacher_readonly_fields_no_topic = ('student', 'topic', 'finalthesisdoc', 'comment', 'score', 'review_state',)
superuser_readonly_fields = ('topic', 'finalthesisdoc',)

superuser_fields = ('student', 'topic', 'finalthesisdoc', 'comment', 'score', 'review_state',)
teacher_fields = ('student', 'topic', 'finalthesisdoc', 'comment', 'score', 'review_state',)

def get_year(self, obj):
    return obj.student.year
# 甚至可以动态更改属性的描述
get_year.short_description = u'年份'
get_year.admin_order_field = '-student__year'
def create_at(self, obj=None):
    return datetime.datetime.fromtimestamp(obj.create_at)

2. 自定义列表字段html标签返回

class WeiboUserAdmin(admin.ModelAdmin):
def expires_time(self, obj):
    return datetime.datetime.fromtimestamp(obj.expires_at)
expires_time.short_description = u'授权过期时间'

def refresh(self,obj):
    btn_str = '<a class="btn btn-xs btn-danger" href="{}">{}</a>'
    return format_html(btn_str,'http://www.google.com',obj.uid)
refresh.short_description = u'更新授权'
# 注意要记得把这个方法放到现实列表里
list_display = ('nick','uid','access_token','expires_time','refresh')
1459653892756
1459653892756

这样你的表单上就会出现列按钮,同样的,你可以为此定义一个显示头像的方法

3. 下拉框列表过滤

def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
    # 是超级管理员就全部跳过
    if request.user.is_superuser:
        pass
    # 不是超级管理员并且字段符合的话,就进行过滤
    elif db_field.name == 'official':
        kwargs['queryset'] = Official.objects.filter(user=request.user)
    return super(FilterAdmin, self).formfield_for_foreignkey(db_field, request=None, **kwargs)

下拉框过滤

1459746103458
1459746103458

竟然全部都是动态的字段,感觉很不安全啊