django_admin详解(2)

1.关于Admin的列表的基本设置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class NotesAdmin(admin.ModelAdmin):
list_display = ('title', 'type', 'note_author', 'key_word', 'praise', 'read_counts', 'status', 'publish_date')
# 按照type降序排列
ordering = ('-type',)
# 绑定actions方法
actions = ['make_published', 'make_draft', 'confirm_author']
# 动作按钮在上方
actions_on_top = True
# list_per_page设置每页显示多少条记录,默认是100条
list_per_page = 20
# 设置可以选择的编辑字段
list_editable = ('type',)
# 搜索字段
search_fields = ('type',)

2.筛选过滤器:

1
list_filter = ('title', 'type', 'key_word', 'status')  # 过滤器

3.为不同字段结果添加不同的颜色

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 函数名为字段名,返回html,反正最后模型都会转为html显示
def colored_status(self):
global color_code
if self.status == 'p':
color_code = 'green'
elif self.status == 'd':
color_code = 'red'
return format_html(
'<span style="color:{};font-size:20px;font-weight:bolder;">{}</span>',
color_code,
self.status
)
# 修改标题
colored_status.short_description = '文章状态'

4.根据不同的用户过滤不同的数据

1
2
3
4
5
6
7
# 重写get_querset方法
def get_queryset(self, request):
all_result = super().get_queryset(request)
if request.user.is_superuser:
return all_result
else:
return all_result.filter(ips_author=request.user)

5.删除一些动作权限

1
2
3
4
5
6
7
8
9
10
def get_actions(self, request):
# 在actions中去掉‘删除’操作
actions = super().get_actions(request)
if not request.user.is_superuser:
# 根据权限删除
if 'can delete information' in actions:
del actions['can delete information']
if 'can add information' in actions:
del actions['can add information']
return actions

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!