Search code examples
djangodjango-admin

Django Admin Action Confirmation Page


In my Django project I have an admin action which requires an confirmation page. I oriented it on the delete_selected action, but it does not work. Here is what I have.

part of my admin.py

def my_action(modeladmin, request, queryset):
    if request.POST.get('post'):
        print "Performing action"
        # action code here
        return None
    else:
        return TemplateResponse(request, "admin/my_action_confirmation.html")

admin/my_action_confirmation.html

<form action="" method="post">{% csrf_token %}
    <div>
        <input type="hidden" name="post" value="yes" />
        <input type="hidden" name="action" value="my_action" />
        <input type="submit" value="Confirm" />
    </div>
</form>

This works almost. I get to the confirmation page but if I click "confirm" I just get back to the original page. The part with the action code is never reached. In fact the my_action function isn't called a second time. So how do I tell django, that the my_action function should be called a second time, once I clicked confirm?


Solution

  • Edit: I was missing more than I thought

    The corrected my_action

    def my_action(modeladmin, request, queryset):
        if request.POST.get('post'):
            print "Performing action"
            # action code here
            return None
        else:
            request.current_app = modeladmin.admin_site.name
            return TemplateResponse(request, "admin/my_action_confirmation.html")
    

    admin/my_action_confirmation.html

    {% load l10n %}
    <form action="" method="post">{% csrf_token %}
        <div>
            {% for obj in queryset %}
            <input type="hidden" name="{{ action_checkbox_name }}" value="{{ obj.pk|unlocalize }}" />
            {% endfor %}
            <input type="hidden" name="post" value="yes" />
            <input type="hidden" name="action" value="my_action" />
            <input type="submit" value="Confirm" />
        </div>
    </form>