0
0
DjangoDebug / FixBeginner · 4 min read

How to Prevent CSRF in Django: Simple Fix and Best Practices

To prevent CSRF attacks in Django, always use the built-in CsrfViewMiddleware and include the {% csrf_token %} tag inside your HTML forms. This ensures that every POST request has a valid token that Django checks to block unauthorized requests.
🔍

Why This Happens

CSRF (Cross-Site Request Forgery) happens when a malicious website tricks a user's browser into sending unwanted requests to your Django site without the user's consent. This can cause harmful actions like changing user data or making purchases.

If you do not protect your forms with CSRF tokens, Django cannot verify if the request is from a trusted source, leaving your site vulnerable.

python
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def unsafe_view(request):
    if request.method == 'POST':
        # Process form data without CSRF protection
        return render(request, 'success.html')
    return render(request, 'form.html')
Output
No CSRF token error because protection is disabled, but site is vulnerable to CSRF attacks.
đź”§

The Fix

Enable Django's CSRF protection by removing @csrf_exempt and ensuring CsrfViewMiddleware is active in your settings.py. Also, add {% csrf_token %} inside your HTML form to include the token in POST requests.

python
from django.shortcuts import render

def safe_view(request):
    if request.method == 'POST':
        # Process form data safely
        return render(request, 'success.html')
    return render(request, 'form.html')
Output
Form submits successfully only if CSRF token is present and valid.
🛡️

Prevention

Always keep CsrfViewMiddleware enabled (it is by default in Django). Use the {% csrf_token %} tag inside every POST form in your templates. Avoid disabling CSRF protection unless absolutely necessary.

Use Django’s csrf_protect decorator for views that need explicit protection. Regularly test your forms to ensure tokens are included and validated.

⚠️

Related Errors

Common related errors include:

  • 403 Forbidden CSRF verification failed: Happens when the CSRF token is missing or invalid in a POST request.
  • Missing CSRF token in AJAX requests: You must include the CSRF token in AJAX headers or data.

Fix these by adding {% csrf_token %} in forms and configuring AJAX to send the token.

âś…

Key Takeaways

Always enable Django's CsrfViewMiddleware to protect against CSRF attacks.
Include {% csrf_token %} inside every HTML form that submits POST requests.
Never disable CSRF protection unless you have a very good reason.
Use csrf_protect decorator for explicit CSRF protection on views.
Test your forms and AJAX requests to ensure CSRF tokens are sent and validated.