Cross-Site Request Forgery (CSRF) is a security attack where a malicious user performs unauthorized actions on behalf of a logged-in user. Django provides built-in CSRF protection to prevent such attacks.
// Django template with CSRF protection
{% extends "base.html" %}
{% block content %}
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
{% endblock %}
// AJAX request including CSRF token
$.ajax({
type: "POST",
url: "/submit-form/",
headers: {
'X-CSRFToken': '{{ csrf_token }}'
},
success: function() {
alert("Form submitted successfully!");
}
});
// Disabling CSRF protection using decorator
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
@csrf_exempt
def my_view(request):
return JsonResponse({"message": "Success"})
When CSRF protection is enabled, Django validates the token before processing requests. Missing or incorrect tokens trigger security errors.
Simulate a sensitive action (like a bank transfer). Toggle the checkbox to decide if you want to include the valid security token or not.