开发者

How to notify user when django's custom action doesn't behave as expected?

开发者 https://www.devze.com 2022-12-20 08:59 出处:网络
I am writing a custom action for django admin. This action should only work for records having particular state.

I am writing a custom action for django admin. This action should only work for records having particular state.

For example "Approve Blog" custom action should approve user blog only when blog is not approved. And it must not appove rejected blogs.

One option is to filter non approved blogs and then approve them. But there are still chances that rejected blogs can be approved.

If user try to approve rejected blog, custom action should notify user about invali开发者_如何学JAVAd operation in the django admin.

Any solution?


The documentation on admin actions is quite helpful, so go take a look!

I think just writing an action that only updates non-rejected blogs ought to do.

The following code assumes you've got variables rejected and approved that map to the integral values representing Blogs that have been rejected, and blogs that have been approved respectively:

class BlogAdmin(admin.ModelAdmin):

    ...
    actions = ['approve']
    ...

    def approve(self, request, queryset):
        rejects = queryset.filter(state = rejected)
        if len(rejects) != 0:
            # You might want to raise an exception here, or notify yourself somehow
            self.message_user(request,
                              "%s of the blogs you selected were already rejected." % len(rejects))
            return

        rows_updated = queryset.update(state = approved)
        self.message_user(request, "%s blogs approved." % rows_updated)
    approve.short_description = "Mark selected blogs as approved"
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号