简介: 在Django自带的admin后台,列表页是我们经常需要进行自定义开发的页面之一。本文将重点介绍列表页的定制开发,包括list_display
的使用和action
的开发。
一、list_display的应用
list_display
用于配置在列表页显示哪些字段,以及如何显示。但是,它不能直接显示多对多的字段,或者显示模型中原本不存在的字段或方法。为了解决这个问题,我们可以定义一个自定义方法,并在list_display
中引用该方法。
pythonCopy code
from django.contrib import admin from django.utils.safestring import mark_safe @admin.register(WxMenu) class MenuAdmin(admin.ModelAdmin): # ... @mark_safe def detail(self, obj): rv = "" if obj.type == WxMenu.Event.CLICK: rv = obj.content.get("key") elif obj.type == WxMenu.Event.VIEW: rv = '<a href="{0}">{1}</a>'.format(obj.content.get("url"), "链接") elif obj.type == WxMenu.Event.MINIPROGRAM: rv = obj.content["appid"] return rv or "" detail.short_description = "详细" list_display = ( "...", "detail", "...")
这里,我们定义了一个detail
方法,根据不同的obj.type
返回不同的值,然后在list_display
中使用这个方法。
二、action的开发
Action是Django admin中一个强大的功能,允许我们对选中的对象执行批量操作。一个Action必须携带三个参数:当前的ModelAdmin、当前的HttpRequest对象(即request)和被选择的对象(即QuerySet)。
pythonCopy code
from django.contrib import admin from django.http import HttpResponse, HttpResponseRedirect import requests import json @admin.register(WxMenu) class MenuAdmin(admin.ModelAdmin): # ... def wxmenu_create(self, request, queryset): token = get_accesstoken() url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + token menu = { # ... your menu data here ... } response = requests.post(url, data=json.dumps(menu, ensure_ascii=False).encode('utf8')) if response.json() is None: return HttpResponse('success') elif response.json()['errmsg'] == 'ok': return HttpResponse('菜单创建成功') else: return HttpResponse('failed') def wxmenu_sync(self, request): # ... your menu sync logic here ... return HttpResponseRedirect('/wxmenu/') def get_urls(self): urls = super().get_urls() my_urls = [ path('wxmenu_sync/', self.admin_site.admin_view(self.wxmenu_sync), name='wxmenu_sync'), path('wxmenu_create/', self.admin_site.admin_view(self.wxmenu_create), name='wxmenu_create'), ] return my_urls + urls actions = ['wxmenu_sync', 'wxmenu_create'] wxmenu_sync.action_type = 0 wxmenu_sync.action_url = "wxmenu_sync" wxmenu_sync.short_description = '同步远程菜单' wxmenu_create.action_type = 0 wxmenu_create.action_url = "wxmenu_create" wxmenu_create.short_description = '发布菜单'
这里我们定义了两个Action:wxmenu_sync
用于同步远程菜单,wxmenu_create
用于发布菜单。需要注意的是,为了使Action生效,我们还需要通过get_urls
方法添加相应的URL映射。
暂无评论内容