0
0
Djangoframework~5 mins

CSRF protection mechanism in Django

Choose your learning style9 modes available
Introduction

CSRF protection stops bad websites from tricking you into doing things you don't want. It keeps your actions safe.

When you have forms that change data on your website, like login or signup forms.
When users submit information that should be secure, like passwords or payments.
When you want to make sure only your website can send requests to your server.
When you want to protect your users from attacks that use their login without permission.
Syntax
Django
In Django templates, use {% csrf_token %} inside your <form> tags.

In views, Django middleware automatically checks the CSRF token for POST requests.

The {% csrf_token %} tag adds a hidden input with a secret token to your form.

Django's CSRF middleware checks this token on form submission to confirm the request is safe.

Examples
This form includes the CSRF token to protect the POST request.
Django
<form method="post">
  {% csrf_token %}
  <input type="text" name="name">
  <button type="submit">Send</button>
</form>
You can disable CSRF protection for specific views using @csrf_exempt, but use it carefully.
Django
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def my_view(request):
    # This view will not check CSRF tokens
    pass
Sample Program

This Django view shows a form with CSRF protection. When you submit your name, it greets you.

Django
from django.shortcuts import render
from django.http import HttpResponse

# View to show form

def my_form(request):
    if request.method == 'POST':
        name = request.POST.get('name', '')
        return HttpResponse(f"Hello, {name}!")
    return render(request, 'form.html')

# form.html content:
# <form method="post">
#   {% csrf_token %}
#   <input type="text" name="name" placeholder="Enter your name">
#   <button type="submit">Submit</button>
# </form>
OutputSuccess
Important Notes

Always include {% csrf_token %} in your POST forms to avoid errors.

CSRF protection works automatically if you use Django's middleware and template tags.

Disabling CSRF protection can make your site vulnerable, so only do it if you understand the risks.

Summary

CSRF protection keeps your site safe from unwanted actions by other sites.

Use {% csrf_token %} in forms to add a secret token.

Django checks this token automatically to allow only safe requests.