There is a django.middleware.csrf.CsrfViewMiddleware
middleware in Django that provides global csrf checking. Its principle is <form>
to generate a hidden label in the <input>
label, submit this hidden <input>
together when submitting the form, and the server verifies that this field is correct.
The official csrf operation steps are:
- In
MIDDLEWARE_CLASSES
addingdjango.middleware.csrf.CsrfViewMiddleware
, open global csrf protection. - For the form from POST to the station
<form>
, add a{% csrf_token %}
template tag to the tag in the template. - Make sure to use the
django.template.context_processors.csrf
Context processor in the corresponding view function . There are two ways to achieve:
(1). UseRequestContext
or directly use the common view, they will be automaticallycsrf_token
added to the template context.
return render_to_response ("xxx.html", context_instance = RequestContext (request))
(2). Manually import and use the processor to generate the CSRF token and add it to the template context. For example:
from django.shortcuts import render_to_response
from django.template.context_processors import csrf
def my_view (request):
c = {}
c.update (csrf (request))
# ... view code here
return render_to_response ("a_template.html" , c)
However, manual import is cumbersome and makes the code difficult to maintain, and RequestContext
it is not good to use , and the Django 1.8 documentation states that context_instance
it will be discarded after 1.8.
How should we deal with csrf_token
it? In fact, Django provides a shortcut function to deal with this problem. An example of
django.shortcuts.render
setting the context_instance
default internally RequestContext
. The call render
can be automatically csrf_token
added to the context.
There are some blogs on the Internet that can be settings
set to TEMPLATE_CONTEXT_PROCESSORS
achieve global csrf_token
padding to the context.
But after my experiment, I found that it is not easy to use. If a friend knows the reason, I would also like to let you know.
I settings
set it up like this:
TEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS + (
'django.core.context_processors.csrf',
)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
自此了解到要想django自带的csrf组件生效,要满足以上三个条件
- In
MIDDLEWARE_CLASSES
addingdjango.middleware.csrf.CsrfViewMiddleware
, open global csrf protection. - For the form from POST to the station
<form>
, add a{% csrf_token %}
template tag to the tag in the template. - Render view with render function