返回文章列表文章索引阅读全文
STARBLOG / 阅读手记
Django

Add a Custom Action to Django Admin and Remove the Restriction of Having to Select Objects

Introduction I have to say, Django's Admin really brings a lot of convenience to development. Here I am tinkering again, this time adding a custom action You can check the official documentation for this custom Action; it's very detailed, so I won't repeat it. https://docs.djangoproject.com/en/3.0/ref/contrib/admin/actions/ UI Effect By default, after adding an action in Django, you have to select objects below before you can submit, but I don't need

曦远 (DealiAxy)约 10 分钟
目录7 个章节

Introduction

I have to say, Django's Admin really brings a lot of convenience to development. Here I am tinkering again, this time adding a custom action.

You can check the official documentation for this custom Action; it's very detailed, so I won't repeat it.

https://docs.djangoproject.com/en/3.0/ref/contrib/admin/actions/

UI Effect

By default, after adding an action in Django, you have to select objects below before you can submit. But I don't need that—I just want to simply click Start Lottery and have the prize drawn right away. Persistence pays off; I still found a solution on Stack Overflow, (SOF-oriented programming, as expected)

Next, I'll explain how to implement it~

Define the Action

Write the following code in admin.py:

@admin.register(models.PrizeLog)
class PrizeLogAdmin(admin.ModelAdmin):
    actions = ['draw_prize']

    def draw_prize(self, request, queryset):
        pass

    draw_prize.short_description = '开始抽奖'
    draw_prize.type = 'warning'
    draw_prize.confirm = '确认即开始抽奖并发送中奖通知~'

This will display the button, but clicking it still won't execute the code inside the draw_prize method, because Django requires at least one object to be selected before an action can run.

Next, we'll take a roundabout approach to bypass this restriction.

Remove the Restriction

Still in this Admin class, write the following code:

@admin.register(models.PrizeJoinLog)
class PrizeJoinLogAdmin(admin.ModelAdmin):
    actions = ['draw_prize']

    def changelist_view(self, request, extra_context=None):
        try:
            action = self.get_actions(request)[request.POST['action']][0]
            action_acts_on_all = action.acts_on_all
        except (KeyError, AttributeError):
            action_acts_on_all = False

        if action_acts_on_all:
            post = request.POST.copy()
            post.setlist(admin.helpers.ACTION_CHECKBOX_NAME,
                         self.model.objects.values_list('id', flat=True))
            request.POST = post

        return super(PrizeJoinLogAdmin, self).changelist_view(request, extra_context)

    def draw_prize(self, request, queryset):
        pass

    draw_prize.short_description = '开始抽奖'
    draw_prize.type = 'warning'
    draw_prize.confirm = '确认即开始抽奖并发送中奖通知~'
    draw_prize.acts_on_all = True

Note the code above: we added the changelist_view method, and in the last line we added an acts_on_all attribute to draw_prize and set it to True (that's the invincible dynamic language Python for you)

This way, when submitting, changelist_view detects that the action has an acts_on_all attribute and automatically includes all objects—equivalent to automatically checking all objects for us. Pretty neat~

Discussion Welcome

This approach doesn't feel entirely perfect though. If you experts have a better solution, feel free to leave a comment and discuss~

References

Discussion Welcome

I've compiled a series of technical articles and materials. Reply with linux, flutter, c#, netcore, android, kotlin, java, python, etc. in the backend of the WeChat official account "Programming Lab" to get related technical articles and materials. If you have any questions, you can also leave a message in the official account backend~

_EOF_

Add a Custom Action to Django Admin and Remove the Restriction of Having to Select Objects

本文作者:
程序设计实验室
版权声明:
本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!

相关文章

一小时完成后台开发:DjangoRestFramework开发实践

DjangoRestFramework开发实践 在这之前我写过一篇关于Django与Drf快速开发实践的博客,Django快速开发实践:Drf框架和xadmin配置指北,粗略说了一下Drf配置和基本使用,不过里面只是涉及到最基本的CRUD,在正常的后端开发中涉及的诸如认证和权限、消息队列、缓存之类的操作,上一篇博客并没有涉及,这次开发我仔细了看了官方文档的这几个部分,把这部分的功能完善了起来。 D

2021-12-18 · Django · 约 1 分钟

Django-Import-Export插件关于外键的处理

前言 Django-Import-Export是一款很好用很方便的Django数据导出导入插件,可以和DjangoAdmin管理后台完美集成,只需要少量的代码配置即可方便实现你要的多种格式导出导入,关于这个插件的使用更多可以看我之前的文章:这里放文章链接 之前我在使用中都是专门做了一个原始数据的表来存导入的数据,然后再对原始数据表做一些数据处理,把数据存到其他表才能真正使用这些数据。(不是很好的做

2022-04-02 · Django · 约 1 分钟

讨论

共 0 条

良言一句三冬暖,恶语伤人六月寒。

加载评论中…