- 在模板的表單裏面添加{% csrf_token %}
{% csrf_token %} - 使用裝飾器 https://docs.djangoproject.com/en/1.9/ref/csrf/
The decorator method¶
Rather than adding CsrfViewMiddleware as a blanket protection, you can use the csrf_protect decorator, which has exactly the same functionality, on particular views that need the protection. It must be used both on views that insert the CSRF token in the output, and on those that accept the POST form data. (These are often the same view function, but not always).
Use of the decorator by itself is not recommended, since if you forget to use it, you will have a security hole. The ‘belt and braces’ strategy of using both is fine, and will incur minimal overhead.
csrf_protect(view)¶
Decorator that provides the protection of CsrfViewMiddleware to a view.
Usage:
from django.views.decorators.csrf import csrf_protect
from django.shortcuts import render
@csrf_protect
def my_view(request):
c = {}
# …
return render(request, “a_template.html”, c)
If you are using class-based views, you can refer to Decorating class-based views.