You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
DjangoBlog/oauth/admin.py

74 lines
2.6 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import logging
from django.contrib import admin
# Register your models here.
from django.urls import reverse
from django.utils.html import format_html
# 获取日志记录器,用于调试或记录错误
logger = logging.getLogger(__name__)
# 自定义 OAuthUser 模型在 Django 后台的展示方式
class OAuthUserAdmin(admin.ModelAdmin):
# 可搜索字段(后台右上角搜索框)
search_fields = ('nickname', 'email')
# 每页显示的记录数
list_per_page = 20
# 在后台列表页显示的字段列
list_display = (
'id',
'nickname',
'link_to_usermodel', # 自定义方法:显示关联的用户链接
'show_user_image', # 自定义方法:显示头像缩略图
'type',
'email',
)
# 列表中可点击进入详情页的字段
list_display_links = ('id', 'nickname')
# 右侧筛选器
list_filter = ('author', 'type',)
# 只读字段(此处先留空,稍后在 get_readonly_fields 动态设置)
readonly_fields = []
# 动态设置只读字段:让所有字段都变为只读,禁止编辑
def get_readonly_fields(self, request, obj=None):
return list(self.readonly_fields) + \
[field.name for field in obj._meta.fields] + \
[field.name for field in obj._meta.many_to_many]
# 禁止在后台手动添加 OAuthUser
def has_add_permission(self, request):
return False
# 在后台列表中显示用户模型的跳转链接
def link_to_usermodel(self, obj):
if obj.author:
# 获取关联用户的 app_label 和 model_name用于反向生成后台编辑页面链接
info = (obj.author._meta.app_label, obj.author._meta.model_name)
link = reverse('admin:%s_%s_change' % info, args=(obj.author.id,))
# 返回带 HTML 的超链接
return format_html(
u'<a href="%s">%s</a>' %
(link, obj.author.nickname if obj.author.nickname else obj.author.email)
)
# 在后台列表中显示用户头像(缩略图)
def show_user_image(self, obj):
img = obj.picture
return format_html(
u'<img src="%s" style="width:50px;height:50px"></img>' % (img)
)
# 修改后台列标题显示名称
link_to_usermodel.short_description = '用户'
show_user_image.short_description = '用户头像'
# 自定义 OAuthConfig 模型在后台的展示方式
class OAuthConfigAdmin(admin.ModelAdmin):
# 在后台列表中显示的字段
list_display = ('type', 'appkey', 'appsecret', 'is_enable')
# 右侧筛选器
list_filter = ('type',)