1

I need to use JS confirmation instead of django's HTML confirm. Here I found a solution of my problem, but there is no code example. Please, help and give me some code. Here is my View:

class EmployeeDelete(DeleteView):
    model = Employees
    template_name = "employees_confirm_delete.html"
    success_url = "/"

And here is model:

class Employees(models.Model):
    first_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=20)
    active = models.BooleanField()
    description = models.TextField(max_length=100)

And here is a part of URL, that deletes an object: /employee/{{ object.id }}/delete

1 Answer 1

5

Here is the code, that will do it.

But first, make sure, that you have 'django.middleware.csrf.CsrfViewMiddleware' in MIDDLEWARE_CLASSES in your settings.py file. It is there by default and this will protect from csrf attacks.

urls.py

urlpatterns = patterns('main.views',
    # ...
    url(r'^employee/(?P<pk>\d+)/delete/$', EmployeeDelete.as_view(), name='delete_employee'),
    # ...
)

views.py

from django.views.generic import  DeleteView
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.http import HttpResponse
from django.utils import simplejson as json


class EmployeeDelete(DeleteView):
    model = Employees
    template_name = "employees_confirm_delete.html"
    success_url = "/"

    # allow delete only logged in user by appling decorator
    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        # maybe do some checks here for permissions ...

        resp = super(EmployeeDelete, self).dispatch(*args, **kwargs)
        if self.request.is_ajax():
            response_data = {"result": "ok"}
            return HttpResponse(json.dumps(response_data),
                content_type="application/json")
        else:
            # POST request (not ajax) will do a redirect to success_url
            return resp

some template, where links to delete employee are present (look here for ajax csrf protection)

{% for e in employees %}
    <a class="delete" href="{% url 'delete_employee' e.id %}"> Delete employee {{e.id}}</a>
{% endfor %}

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>

<script type="text/javascript">
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    $(document).ready(function() {

        var csrftoken = getCookie('csrftoken');

        function csrfSafeMethod(method) {
            // these HTTP methods do not require CSRF protection
            return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
        }
        $.ajaxSetup({
            crossDomain: false, // obviates need for sameOrigin test
            beforeSend: function(xhr, settings) {
                if (!csrfSafeMethod(settings.type)) {
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                }
            }
        });

        // This function must be customized
        var onDelete = function(){
            $.post(this.href, function(data) {
                if (data.result == "ok"){
                    alert("data deleted successfully");
                } else {
                    // handle error processed by server here
                    alert("smth goes wrong");
                }
            }).fail(function() {
                // handle unexpected error here
                alert("error");
            });
            return false;
        }

        $(".delete").click(onDelete);
    });
</script>

You just need to customize the behaviour of onDelete js function.

Sign up to request clarification or add additional context in comments.

1 Comment

You can use something like myclabs.github.io/jquery.confirm for the confirmation (or code it yourself with javascript/jquery)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.