Dear team,

I've been trying to come up with a generic way of confirming an action
(e.g. deleting an item) in a Django application. A decorator would be
neat, I think. But I was a bit surprised that I didn't find anything
on the issue in the documentation or forums (except for
django.views.generic.create_update.delete_object, but that's not quite
what I'm after).

Well, my initial solution is something like this:


# --- clip ---
# The decorator.
def confirm_view_operation(cancel_url='', question=''):
        def decorator(func):
        def inner(request, *args, **kwargs):
            if request.POST:
                if request.POST.has_key('yes'):
                    # User chose yes, execute the view function.
                    return func(request, *args, **kwargs)
                # User chose cancel, redirect to cancel url.
                return HttpResponseRedirect(cancel_url)

            tmpl = loader.get_template('confirm.html')
            cont = RequestContext(request, {
                'question': question,
            })
            return HttpResponse(tmpl.render(cont))
        return inner
    return decorator

# A random view function.
@confirm_view_operation(cancel_url='/some/url', question='Are you sure
you want to remove the product?')
delete_product(request, product_id):
    # delete the item and redirect to product listing...
# --- clip ---


The idea is that the decorator can be used to confirm any view
regardless of what the view function is actually doing (deleting an
item was just an example). Adding the confirm view to any view
function is of course very simple with the decorator.

One problem is that I can't figure out how to have a reference to an
actual item in the database. For example, how to pass a question
string such as "Are you sure you want to delete the product Magic
Bullet?" to the decorator?

I'm sure there are other shortcomings in my solution. But does anyone
have any suggestions to improve the decorator or perhaps have an
entirely different approach to solving the problem?


Mikko


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to