python之Django学习笔记(五)---后台(admin.py)Action使用
Action即在列表界面字段上面的一个插件
默认只有一个删除动作:Delete selected 表名。这可以禁用这个action,在admin.py中增加一行如下代码:
class StudentAdmin(admin.ModelAdmin): list_display = ('NameNo','Sex_color','Age') admin.site.register(Student,StudentAdmin) admin.site.disable_action('delete_selected')#禁用默认Action
禁掉删除功能,也可以自定义一个删除功能:
def delete_selected(modeladmin,request,queryset):#自定义删除动作 a = queryset.delete()[0] if a == 1: message = '1 item is deleted!' else: message = '%d items are deleted!'%a modeladmin.message_user(request, message) delete_selected.short_description = '删除选中项' class StudentAdmin(admin.ModelAdmin): list_display = ('NameNo','Sex_color','Age') actions = (delete_selected,)#添加自定义动作到Action中
刷新界面可以看到Aciton里面已经有了新添加的动作:
这里是重写了delete_selected这个方法,所以即使上面没有禁用这个方法,这里也会只显示添加的方法。(若不加入action中,还是会显示原来的方法)
当然也可以把Delete_selected这个动作用到所有的模型中,和禁用类似,只需一行代码:
admin.site.add_action(delete_selected)#所有模型都有此动作
actions:
既然这样,也可以自定义其他动作,然后加入到Action中,比如修改选中记录的性别为female或者male
在admin.py中添加如下代码:
def change_sex_female(modeladmin,request,queryset): a = queryset.update(Sex = 'F') if a == 1: message = '1 item is updated to Female!' else: message = '%d items are updated to Female!'%a modeladmin.message_user(request,message)#修改成功后的提示 change_sex_female.short_description = '修改性别为Female' def change_sex_male(modeladmin,request,queryset): a = queryset.update(Sex = 'M') if a == 1: message = '1 item is updated to Male!' else: message = '%d items are updated to Male!'%a modeladmin.message_user(request,message)#修改成功后的提示 change_sex_male.short_description = '修改性别为Male' class StudentAdmin(admin.ModelAdmin): list_display = ('NameNo','Sex_color','Age') actions = (delete_selected,change_sex_female,change_sex_male,)#把自定义的俩个动作加入Action
上述代码中增加俩个动作change_sex_female和change_sex_male,然后在StudentAdmin中把这俩个动作加入了actions中,刷新界面可以看到已经增加了俩个Action:
可以选择几条数据,然后执行,会有相关提示:
也可以根据当前性别进行反转操作:
def change_sex(modeladmin,request,queryset): if queryset.filter(Sex='F').count() == 1 or queryset.filter(Sex='M').count() == 1: if queryset.filter(Sex='F'): queryset.update(Sex='M') message = 'Item is changed to Male!' else: queryset.update(Sex='F') message = 'Item is changed to Female!' else: message = 'Can\'t select more than 1 item!' modeladmin.message_user(request,message) change_sex.short_description = '性别反转' class StudentAdmin(admin.ModelAdmin): list_display = ('NameNo','Sex_color','Age') actions = (change_sex_female,change_sex_male,delete_selected,change_sex,)
如果actions设置为None,则不会出现Action这个插件
同样,如果设置禁用Delete_selected动作并且没有设置其他Action,name也不会出现Aciton这个插件
action_on_top:
默认True显示在顶端,若设置为False则不会显示在顶端
action_on_bottom:
默认False不显示,若设置为True则显示在低端
actions_selection_counter:
默认True,显示插件右侧的统计数,若设置为False,则不会显示统计
资料
https://docs.djangoproject.com/en/dev/ref/contrib/admin/actions/
https://docs.djangoproject.com/en/dev/ref/contrib/admin/