当前位置:  开发笔记 > 编程语言 > 正文

Django DeleteView JavaScript确认

如何解决《DjangoDeleteViewJavaScript确认》经验,为你挑选了1个好方法。

我需要使用JS确认而不是django的HTML确认.在这里,我找到了我的问题的解决方案,但没有代码示例.请帮助并给我一些代码.这是我的观点:

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

这是模型:

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)

这是URL的一部分,删除对象: /employee/{{ object.id }}/delete



1> stalk..:

这是代码,它将做到这一点.

但首先,要确保,你有'django.middleware.csrf.CsrfViewMiddleware'MIDDLEWARE_CLASSES你的settings.py文件.它默认存在,这将防止csrf攻击.

urls.py

urlpatterns = patterns('main.views',
    # ...
    url(r'^employee/(?P\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

一些模板,其中存在删除员工的链接(在这里查看ajax csrf保护)

{% for e in employees %}
     Delete employee {{e.id}}
{% endfor %}




您只需要自定义onDeletejs函数的行为.

推荐阅读
Life一切安好
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有