First, in the Django background processing
1, add the Django setting in the Django.contrib.messages.middleware.MessageMiddleware, the general New Django Project will bring their own.
Middleware_classes = [
' Django.middleware.security.SecurityMiddleware ',
' Django.contrib.sessions.middleware.SessionMiddleware ',
' Django.middleware.common.CommonMiddleware ',
' Django.middleware.csrf.CsrfViewMiddleware ',
' Django.contrib.auth.middleware.AuthenticationMiddleware ',
' Django.contrib.messages.middleware.MessageMiddleware ',
]
2. Add {% CSRF%} from the Templete HTML page, and the background redirection syntax is as follows:
Return Render_to_response (xxx.html ', Context_instance=requestcontext (Request))
Second, the front-end processing
Add the following statement to all AJAX requests:
$ (function () {
$.ajaxsetup ({
Data: {csrfmiddlewaretoken: ' {{csrf_token}} '},
});
})
This request to the background will take the Csrf_token value that the Django generates. The middleware CSRF module will intercept to determine whether the Csrf_token value is consistent, and if so, the request is legitimate.
Third, for Ajax complex objects, such as [{"id": "001", "Name": "Xiao Ming"},{"id": "002", "name": "Small Army"}]., Background post processing
This object must be converted to JSON format to the background, and the background is deserialized. (Do not use the other serialization format of Ajax, after the depth of serialization, Django background parsing is more difficult)
ContentType no need to specify Utf-8, otherwise post parsing error
Iv. CSRF Attack and prevention
CSRF uses session and cookie timeliness to attack. He will obtain the requested cookie and make a request within the session limitation period. Therefore, for important information, important functions are processed on a single request. That is, the request fails once.
For example: The request header is added to the authentication token information, which expires. Django's middleware Csrf_token is what this principle prevents.
Using Django Middleware Django.middleware.csrf.CsrfViewMiddleware to prevent CSRF attacks