1

I have a a template where I can delete using Django DeleteView. I want it the data to be deleted after using the Javascript popup.

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>

After I click the Delete button, there is an error:

CSRF verification failed. Request aborted.

How can I make this work?

1 Answer 1

3

remove type='submit' from the buton

add class or id to the form and then in the js add $('#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();
            }            
        }

Your view is a class you have to add @method_decorator(csrf_exempt) before your logic in your ObjectNameDeleteView()

class ObjectNameDeleteView(View):
       @method_decorator(csrf_exempt)
       #then your logic
Sign up to request clarification or add additional context in comments.

7 Comments

It still shows error: "403 Forbidden CSRF verification failed. Request aborted."
Url('^person_delete/(?P<obj_pk>\d+)/$', views.personDelete, 'person_delete') is that how your url looks like?
Is it a class or a def based view?
Well that means it is a class view in this case put @method_decorator(csrf_exempt) in your ObjectNameDeleteView class ObjectNameDeleteView(View): @method_decorator(csrf_exempt)
I added the @csrf_exempt to the urls.py and it worked Thanks from django.views.decorators.csrf import csrf_exempt path('objects/delete/<int:pk>/', csrf_exempt(views.ObjectNameDeleteView.as_view()), name='person_delete'),
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.