tags:

views:

382

answers:

1

Hi,

I`m thinking of creating an admin action-like behaviour outside the admin. Thus the user should be able to select objects with a checkbox and after selecting an action with the dropdown the selected action is conducted on all selected objects.

I thought of the following approach.

Create a checkbox for each object in the .html template. Result would be this (i took it from the admin):

<td><input type="checkbox" class="action-select" value="24" name="_selected_action" /></td> 

Then create the action dropdown (took it also from the admin):

<div class="actions"> 
            <label>Action: <select name="action"> 
                <option value="" selected="selected">---------</option> 
                <option value="delete_selected">Delete selected contacts</option> 
            </select></label> 
            <button type="submit" class="button" title="Run the selected action" name="index" value="0">Go</button> 
        </div> 

Now i m asking myself how i can map this action dropdown to a python function. Probably a function which i would place inside the model object which i want to apply this action to.

I hope somebody can tell it to me.

The next point would be how i can check in this function which objects have been selected. When i found out how this works, i can work with this objects and return a HttpResponse.

I think that should be everything to create an action like behaviour. Is this correct or is something missing?

Edit: My Solution

Finally I came up with the following solution:

I created a function called action_handler, which takes the request and the model it will act upon. From the post querydicts I get the selected action (request.POST.getitem('action')) and the selected objects (request.POST.getlist('_selected_for_action')).

Based on the input and the process the function returns some values, which tells the calling view what happened in the action_handler.

@login_required
def action_handler(request, model):
    """
    PARAMETERS
    model = the django model upon which the actions are executed

    RETURN VALUES
    0 - POST param action is not available
      - POST param selected_action is not defined
      - selected_ids is empty
      - object_list is empty
    1 - Successfully conducted the delete_selected action
    2 - Successfully conducted the new_selection action

    DESCRIPTION
    handles all actions for arbitrary models
    Action:
        "delete selected" - calls the generic delete method, delete_objects(request, model, selected_ids)
    """
    try:
        selected_action = request.POST.__getitem__('action')
        selected_ids = request.POST.getlist('_selected_for_action')
        object_list = model.objects.filter(pk__in=selected_ids)
        if object_list.count() < 1:
            request.user.message_set.create(message='Please select at least one item!')
            return 0
        if selected_action == 'delete_selected':
            try:
                action_approved = request.POST.__getitem__('action_approved')
                if action_approved == '1':
                    delete_objects(request, model, selected_ids)
                    return 1

            except KeyError:
                #action_approved param is not available
                #show the objects check page for delete approval
                context = {
                    'action_name' : selected_action,
                    'object_list' : object_list,
                }
                return render_to_response("crm/object_delete_check.html", context,
                                       context_instance=RequestContext(request))

        if selected_action == 'new_selection':
            #add the selected objects to a new cs selection
            now = datetime.now()
            stamp = now.strftime("%Y-%m-%d/%H:%M")
            cs_name = 'cs_auto_created_' + str(stamp)
            cs = ContactSelection(id=None, name=cs_name)
            cs.created_by = request.user
            cs.save()
            for object in object_list:
                cs.contacts.add(object)
            request.user.message_set.create(message='Successfully created the %s selection' % cs.name)
            return 2

        request.user.message_set.create(message='This action is not available!')
        return 0

    except KeyError:
        request.user.message_set.create(message='Please select an action!')
        return 0

The delete delete_objects(request, model, selected_ids) looks like this:

@login_required
def delete_objects(request, model, selected_ids):
    '''
    capsulate a bulk delete method
    delete all objects found for the given model
    fails silently since model.delete() always fails silently
    '''
    object_list = model.objects.filter(pk__in=selected_ids)
    count = object_list.count()
    if count == 1:
        name = model._meta.verbose_name.title()
    else:
        name = model._meta.verbose_name_plural.title()
    object_list.delete()
    request.user.message_set.create(message='Successfully deleted %s %s' % (count,name))
    return

This way I'm able to include this action_handler for different views and encapsulate a delete function independend from the model on which the function is acting upon.

+1  A: 

This is a perfect spot for a dynamic form. The general idea is to make a form which lists all of the items to the user and a dropdown menu of actions. So this easily maps to a ModelMultipleChoiceField and a ChoiceField.

from django import forms

def action_formset(qset, actions):
    """A form factory which returns a form which allows the user to pick a specific action to 
    perform on a chosen subset of items from a queryset.
    """
    class _ActionForm(forms.Form):
        items = forms.ModelMultipleChoiceField(queryset = qset)
        actions = forms.ChoiceField(choices = zip(actions, actions))

    return _ActionForm

#in your views.py

def action_view(request):

    qset = Item.objects.all() #some way to get your items
    actions = ('tuple', 'of', 'action', 'names')

    formclass = action_formset(qset, actions)

    if request.method == 'POST':
        #deal with chosen items
        form = formclass(request.POST)
        chosen_action = form.cleaned_data['action']
        chosen_qset = form.cleaned_data['items']
        #do something with items
        return ...

    #deal with a GET request
    form = formclass()

    return ...

Then just display this form in a template like you would any other. Hope that helps.

JudoWill
looks good. i will give it a try tomorrow.
Tom Tom
any luck with it?
JudoWill
actually I did not tried it, since i had another idea how it could works. See my solution above. This works for me. I'm new to django and i did not get the idea with this dynamic form at first sight. I'm using a form based on a model. I think your form factory is a good idea. But when I need forms based on models I don't think it fits. What do you think?
Tom Tom