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.
Django/doc/oauth/admin.py

93 lines
3.7 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
# 注册模型到admin站点
from django.urls import reverse
from django.utils.html import format_html
# 初始化日志记录器,用于记录当前模块的日志信息
logger = logging.getLogger(__name__)
class OAuthUserAdmin(admin.ModelAdmin):
"""
OAuthUser模型的Admin管理类用于在Django admin后台管理第三方登录用户信息
"""
# 配置搜索字段,支持通过昵称和邮箱搜索
search_fields = ('nickname', 'email')
# 配置每页显示20条记录
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',)
# 初始只读字段列表(后续会动态扩展)
readonly_fields = []
def get_readonly_fields(self, request, obj=None):
"""
重写只读字段方法,当编辑对象时,将所有字段设为只读
新增时obj为None不生效编辑时obj存在所有字段只读
"""
if obj: # 编辑已有对象时
# 合并初始只读字段 + 模型所有普通字段 + 所有多对多字段
return list(self.readonly_fields) + \
[field.name for field in obj._meta.fields] + \
[field.name for field in obj._meta.many_to_many]
return self.readonly_fields # 新增时使用初始只读字段
def has_add_permission(self, request):
"""
禁用在admin后台手动添加OAuthUser的权限第三方用户信息应通过登录自动创建
"""
return False
def link_to_usermodel(self, obj):
"""
自定义列表字段生成关联本地用户的admin编辑页链接
"""
if obj.author: # 如果存在关联的本地用户
# 获取关联用户模型的app标签和模型名称
info = (obj.author._meta.app_label, obj.author._meta.model_name)
# 反转生成用户编辑页的URL
link = reverse('admin:%s_%s_change' % info, args=(obj.author.id,))
# 返回带链接的HTML使用format_html确保安全渲染
return format_html(
u'<a href="%s">%s</a>' %
(link, obj.author.nickname if obj.author.nickname else obj.author.email)
# 显示昵称,若昵称不存在则显示邮箱
)
return None # 无关联用户时返回空
def show_user_image(self, obj):
"""
自定义列表字段:显示用户头像图片
"""
img = obj.picture # 获取头像图片URL
if img: # 若头像存在
# 返回图片HTML标签限制宽高为50px
return format_html(u'<img src="%s" style="width:50px;height:50px"></img>' % (img))
return None # 无头像时返回空
# 定义自定义字段在列表页的显示名称
link_to_usermodel.short_description = '用户'
show_user_image.short_description = '用户头像'
class OAuthConfigAdmin(admin.ModelAdmin):
"""
OAuthConfig模型的Admin管理类用于在Django admin后台管理第三方登录配置信息
"""
# 配置列表页显示的字段
list_display = ('type', 'appkey', 'appsecret', 'is_enable')
# 配置列表页的过滤条件(按第三方平台类型过滤)
list_filter = ('type',)