添加自定义动作:
例子,添加一个方法,批量更新文章,代码如下:
from django.contrib import admin from myapp.models import Article def make_published(self, request, queryset): rows_updated = queryset.update(status=’p’) if rows_updated == 1: message_bit = "1 story was" else: message_bit = "%s stories were" % rows_updated self.message_user(request, "%s successfully marked as published." % message_bit) class ArticleAdmin(admin.ModelAdmin): list_display = [’title’, ’status’] ordering = [’title’] actions = [make_published] admin.site.register(Article, ArticleAdmin)
效果如下:
自定义动作的权限控制,重载get_actions方法,如下:(只允许名字以J大头的删除记录)
from django.contrib import admin from myapp.models import Article def make_published(self, request, queryset): rows_updated = queryset.update(status=’p’) if rows_updated == 1: message_bit = "1 story was" else: message_bit = "%s stories were" % rows_updated self.message_user(request, "%s successfully marked as published." % message_bit) class ArticleAdmin(admin.ModelAdmin): list_display = [’title’, ’status’] ordering = [’title’] actions = [make_published] def get_actions(self, request): actions = super(MyModelAdmin, self).get_actions(request) if request.user.username[0].upper() != ’J’: if ’delete_selected’ in actions: del actions[’delete_selected’] return actions
时间: 2024-12-28 21:45:20