Reputation: 53
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?
Upvotes: 1
Views: 1912
Reputation: 2035
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
Upvotes: 3