views:

252

answers:

2

Admin actions can act on the selected objects in the list page. Is it possible to act on all the filtered objects?

For example if the admin search for Product names that start with "T-shirt" which results with 400 products and want to increase the price of all of them by 10%. If the admin can only modify a single page of result at a time it will take a lot of effort.

Thanks

+1  A: 

The custom actions are supposed to be used on a group of selected objects, so I don't think there is a standard way of doing what you want.

But I think I have a hack that might work for you... (meaning: use at your own risk and it is untested)

In your action function the request.GET will contain the q parameter used in the admin search. So if you type "T-Shirt" in the search, you should see request.GET look something like:

<QueryDict: {u'q': [u'T-Shirt']}>

You could completely disregard the querystring parameter that your custom action function receives and build your own queryset based on that request.GET's q parameter. Something like:

def increase_price_10_percent(modeladmin, request, queryset):
    if request.GET['q'] is None:
        # Add some error handling
    queryset=Product.objects.filter(name__contains=request.GET['q'])
    # Your code to increase price in 10%
increase_price_10_percent.short_description = "Increases price 10% for all products in the search result"

I would make sure to forbid any requests where q is empty. And where you read name__contains you should be mimicking whatever filter you created for the admin of your product object (so, if the search is only looking at the name field, name__contains might suffice; if it looks at the name and description, you would have a more complex filter here in the action function too).

I would also, maybe, add an intermediate page stating what models will be affected and have the user click on "I really know what I'm doing" confirmation button. Look at the code for django.contrib.admin.actions for an example of how to list what objects are being deleted. It should point you in the right direction.

NOTE: the users would still have to select something in the admin page, otherwise the action function would never get called.

celopes
A: 

Hi I need to achieve exactly the same, but i have lots of filters (not only free search query), so it doesn't really a practical solution to re-search every time a user want to access all of his search results at once...

anything else?

thanks tom

tom