gpt4 book ai didi

javascript - Django DeleteView JavaScript 确认

转载 作者:行者123 更新时间:2023-11-30 08:52:34 25 4
gpt4 key购买 nike

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

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

最佳答案

这是执行此操作的代码。

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

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

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

{% 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>

你只需要自定义onDelete js函数的行为即可。

关于javascript - Django DeleteView JavaScript 确认,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16495645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com