我使用Django DeleteView删除对象。首先,我实现了删除添加确认对话框,重定向另一个html页面。现在,我想添加bootbox弹出窗口。但我不知道在哪里添加代码。请帮忙
models.py
class Review(models.Model):
review_description = models.TextField(max_length=500)
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
book = models.ForeignKey(Book, on_delete=models.CASCADE)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
views.py
class ReviewDelete(DeleteView):
model = Review
template_name = "confirm_delete.html"
def get_success_url(self, *args, **kwargs):
review = get_object_or_404(Review, pk=self.kwargs['pk'])
return reverse("books:detail", args = (review.book.id,))
confirm_delete.html
{% extends "base.html" %}
{% block content %}
<h1>Delete</h1>
<p>Are you sure you want to delete {{ review }}?</p>
<form action="{% url "delete" pk=review.id %}" method="POST">
{% csrf_token %}
<input type="submit" value="Yes, delete." />
<a href="{% url "books:detail" id=review.book.id %}">No, cancel.</a>
</form>
{% endblock %}
book_details.html
<a href="{% url "delete" pk=review.id %}" class="badge badge-danger">Delete</a>
{# <a href="{% url "delete" pk=review.id %}" class="badge badge-danger">Delete</a>#}
base.html文件
<script type="text/javascript">
$(document).ready(function () {
$("#review-delete-btn").click(function (event) {
event.preventDefault();
bootbox.confirm({
title: "Destroy planet?",
message: "Do you want to delete? This cannot be undone.",
buttons: {
cancel: {
label: '<i class="fa fa-times"></i> Cancel'
},
confirm: {
label: '<i class="fa fa-check"></i> Confirm'
}
},
callback: function (result) {
console.log('This was logged in the callback: ' + result);
}
});
});
});
</script>
urls.py
url(r'^reviews/(?P<pk>\d+)/delete/$', ReviewDelete.as_view(), name='delete'),
答案 0 :(得分:0)
假设您的服务器页面在完成删除时没有执行重定向,您只需要在确认回调中添加一个AJAX调用。像这样:
<script>
$(function () {
$("#review-delete-btn").on('click', function (event) {
event.preventDefault();
// for referencing this later in this function
var _button = $(this);
bootbox.confirm({
title: "Destroy planet?",
message: "Do you want to delete? This cannot be undone.",
buttons: {
cancel: {
label: '<i class="fa fa-times"></i> Cancel'
},
confirm: {
label: '<i class="fa fa-check"></i> Confirm'
}
},
callback: function (result) {
// result will be a Boolean value
if(result){
// this encodes the form data
var data = _button.closest('form').serialize();
$.post('your delete URL here', data).
done(function(response, status, jqxhr){
// status code 200 response
})
.fail(function(jqxhr, status, errorThrown){
// any other status code, including 30x (redirects)
});
}
}
});
});
});
</script>
您可能希望查看$.post和serialize的文档。我还建议您按照AJAX主题进行操作 - $ .post是$ .ajax的便捷方法,因此您应该知道如何使用这两种方法。