[Django]-Creating confirmation dialog pages when Javascript is disabled

5👍

I would use Django’s built in DeleteView, which will display a confirmation page for an HTTP GET request and perform deletion for an HTTP POST request.

The documentation gives this example:

from django.views.generic.edit import DeleteView
from django.core.urlresolvers import reverse_lazy
from myapp.models import Author

class AuthorDelete(DeleteView):
    model = Author
    success_url = reverse_lazy('author-list')

I’d recommend reading the documentation for the SingleObjectMixin which explains how to customise the way the view finds the object to delete (the default is to look for an URL keyword argument called pk), and for the TemplateResponseMixin which explains how to customise the template that is used (the default is 'myapp/author_check_delete.html').

This is just one of a number of class-based generic views that make basic operations (displaying a page for a single model instance, for a list of model instances, and handling editing, deletion etc.) very quick and easy to implement.

If you wanted to enhance this with JavaScript later you could always write some unobtrusive JS that detects links to the deletion confirmation page (by looking for a class, or a particular URL) and adds a click handler that pops up a confirmation dialog and then sends a POST request to the URL in the link’s href attribute. You would also need to modify the view slightly to return a JSON object when request.is_ajax() is True, so that your JS would know if the deletion had succeeded or failed, which would probably involve overriding one of the methods inherited from the DeletionMixin.

4👍

That sounds fine. What I have done a couple of times is to create a confirmation template that can be used anywhere in the application:

{% extends 'base.html' %}

{% block content %}

    <div class="confirmation-box">
        <p>{{ message }}</p>
        <div>
            <a href="{{ prev_link }}">Cancel</a>
            <form action="{{ action_link }}" method="post">
                <input type="hidden" name="next" value="{{ prev_link }}" />
                <input type="submit" value="Send" />
            </form>
        </div>
    </div>

{% endblock %}

You pass to it:

  • A confirmation message for the user (message)
  • The url to the page you are in (prev_link)
  • The url that should be called to perform the action (action_link)

If the user cancels the action, then she/he goes back to the original page.

If the user confirms, then the prev_link is passed as a hidden parameter, so the view can redirect the user to the original page after performing the action (although this is completely optional of course).

Which is pretty much what you propossed in your question.

👤pacha

Leave a comment