Django:使用Java确认删除视图,而无需重定向到模板

时间:2018-08-02 06:55:36

标签: django django-forms django-templates django-views django-csrf

我有一个模板,可以使用Django DeleteView进行删除。我希望使用Javascript弹出窗口后将其删除。

Views.py

class ObjectNameDeleteView(DeleteView):
    model = ObjectName
    form_class = PostObjectName   
    success_url = 'http://localhost:8000/impact/displayobjects/'

DisplayObjects.html

<form method="POST" action="{% url 'person_delete' obj.pk %}">
{% csrf_token %}
<a href="{% url 'person_delete' obj.pk %}">
<button type="submit" class="btn btn-danger" onClick="deleteFunction()">Delete</button></a>
</form>

<script>
        function deleteFunction(e) {
            if(!confirm("Are you sure you want to delete?")){
                e.preventDefault();
            }            
        }
</script>

单击“删除”按钮后,出现错误:

CSRF验证失败。请求已中止。

我该如何做?

1 个答案:

答案 0 :(得分:2)

从臀部删除type='submit'

将类或ID添加到表单中,然后在js中添加 $('#your-form-id').submit();

<form id='person-delete' method="POST" action="{% url 'person_delete' obj.pk %}">
{% csrf_token %}
<a href="{% url 'person_delete' obj.pk %}">
<button  class="btn btn-danger" onClick="deleteFunction()">Delete</button></a>
</form>


 function deleteFunction(e) {
            if(!confirm("Are you sure you want to delete?")){
                e.preventDefault();
            }else{
             $('#person-delete').submit();
            }            
        }

您的视图是一类,您必须在@method_decorator(csrf_exempt)中的逻辑之前添加ObjectNameDeleteView()

class ObjectNameDeleteView(View):
       @method_decorator(csrf_exempt)
       #then your logic