views:

37

answers:

1

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 invalid operation in the django admin.

Any solution?

+1  A: 

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"
Dominic Rodger
This is how I would do it but I think the OP's question is silly, on the basis of "What if you want to un-reject something?". Now the OP needs a custom action `unreject` that is equivalent to `approve` but only for Rejected items, that either puts it back to Draft or Approved status. Otherwise something can be irreversibly Rejected.
jonwd7
@jonwd7 - not really - presumably you could still go in and edit the Blog to give it draft or approved status, you just can't *bulk* update blogs.
Dominic Rodger
Thank you very much Rodger...
Software Enthusiastic