gpt4 book ai didi

django - 转换 Django DeleteView 以使用 ajax

转载 作者:行者123 更新时间:2023-12-05 06:16:32 29 4
gpt4 key购买 nike

我是 django 的新手,我遇到了 ajax 的问题。我有下面的代码。

我有一个 django delte View 。我想将它与 ajax 一起使用。现在 View 正在运行,但 CSRF token 未呈现。

作为新手,我想尝试使用基于类的 View 。我不确定为什么 CSRF TOKEN 没有在 AJAX 版本中呈现。它在使用浏览器时出现,但在使用 ajax 时不出现。

有人可以帮忙吗?

view.py

class DeleteOrderItemView(SuccessMessageMixin, generic.DeleteView):
model = OrderItem
template_name = 'pos/order_item_confirm_delte.html'

# overwritten the delete to have a conformation code. Pending items do not need a conformation code.
def delete(self, *args, **kwargs):
print("I was called !")
self.object = self.get_object()
conformation_code = self.request.POST.get('cancellation_code')

if conformation_code == str(12345) or self.object.status == "Pending":
# Record code and logged in user
messages.success(self.request, "Order item {} deleted.".format(self.object.item.name))

# print cancelled KOT

return super(DeleteOrderItemView, self).delete(*args, **kwargs)

else:
messages.warning(self.request, "Incorrect conformation code.")
return HttpResponseRedirect(reverse('pos:delete_order_item', kwargs={'pk': self.object.pk}))

def get_success_url(self, **kwargs):
self.object = self.get_object()
order_pk = self.object.order.pk
return reverse_lazy('pos:order_details', kwargs={'pk': order_pk})

def render_to_response(self, context, **response_kwargs):
""" Allow AJAX requests to be handled more gracefully """
if self.request.is_ajax():
context = self.get_context_data(**response_kwargs)
rendered = render_to_string(self.template_name, context)

return JsonResponse({'delete_form': rendered}, safe=False, **response_kwargs)
else:
return super(generic.DeleteView, self).render_to_response(context, **response_kwargs)

Javascript

/* Load the delete form */
$("#js_order_list_items").on("click", "#js_remove_item", function(){

$("#modal-actions").modal("show");
remove_url = $('#js_remove_item').attr('js_delete_url')

$.ajax({
url: remove_url,
type: 'get',
dataType: 'json',
beforeSend: function () {
$("#modal-actions").modal("show");
},
success: function (data) {
console.log(data.delete_form)
$("#modal-actions .modal-content").html(data.delete_form)
}
})
});

HTML

{% load static %}
{% block content %}
<div class="container">
<br/>
<div class="col-12 alert alert-danger">
<h4>Delete item for {{ orderitem.order.customer.name }}</h4>
</div>
<div class="row">
<div class="col-6">
<ul class="list-group">
<li class="list-group-item"><strong>{{ orderitem.item.name }}</strong></li>
<li class="list-group-item">Quantity: {{ orderitem.quantity }}</li>
<li class="list-group-item">Price: {{ orderitem.price }}</li>
<li class="list-group-item">Ordered by: {{ orderitem.order.user.username }}</li>
<li class="list-group-item">
{% if messages %}
<div class="alert alert-danger" role="alert">
{% for message in messages %}
{{ message }}
{% endfor %}
</div>
{% endif %}
</li>
</ul>
</div>
</div>
<div class="row">
<div class="col-12">
<hr/>
<form method="POST" action="{% url 'pos:delete_order_item' pk=orderitem.pk %}" class="js_confirm_delete_form">

{% csrf_token %}

{% if orderitem.status == 'Confirmed' %}
<label>Cancellation Code: </label> <input type="password" id="cancellation_code" name="cancellation_code"><br/><hr/>
{% endif %}
<input type="submit" value="Confirm" class="btn btn-danger btn-large btn-lg">
<a href="{% url 'pos:order_details' pk=orderitem.order.pk %}" class="btn btn-default btn-lg"><button class="btn btn-secondary btn-large btn-lg" type="button">Cancel</button> </a>
</form>

</div>
</div>
</div>
{% endblock %}

最佳答案

我自己发现了这个问题。 render_to_string 需要传递给它的请求,csrf_token 才能工作。

rendered = render_to_string(self.template_name, context, request=self.request)

关于django - 转换 Django DeleteView 以使用 ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62066319/

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