djangodjango-admin

django admin action without selecting objects


Is it possible to create a custom admin action for the django admin that doesn't require selecting some objects to run it on?

If you try to run an action without selecting objects, you get the message:

Items must be selected in order to perform actions on them. No items have been changed.

Is there a way to override this behaviour and let the action run anyway?


Solution

  • Yuji is on the right track, but I've used a simpler solution that may work for you. If you override response_action as is done below you can replace the empty queryset with a queryset containing all objects before the check happens. This code also checks which action you're running to make sure it's approved to run on all objects before changing the queryset, so you can restrict it to only happen in some cases.

    def response_action(self, request, queryset):
        # override to allow for exporting of ALL records to CSV if no chkbox selected
        selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
        if request.META['QUERY_STRING']:
            qd = dictify_querystring(request.META['QUERY_STRING'])
        else:
            qd = None
        data = request.POST.copy()
        if len(selected) == 0 and data['action'] in ('export_to_csv', 'extended_export_to_csv'):
            ct = ContentType.objects.get_for_model(queryset.model)
            klass = ct.model_class()
            if qd:
                queryset = klass.objects.filter(**qd)[:65535] # cap at classic Excel maximum minus 1 row for headers
            else:
                queryset = klass.objects.all()[:65535] # cap at classic Excel maximum minus 1 row for headers
            return getattr(self, data['action'])(request, queryset)
        else:
            return super(ModelAdminCSV, self).response_action(request, queryset)