For blog reposted, please indicate the source!
Author: Yu XiaoYu
Link: http://blog.csdn.net/zgyulongfei/article/details/8830750
Let me restore the error page first:
This mistake left me alone for a long morning. I searched for a lot of answers on the Internet, and the general solution was the same. I followed them, but the error still exists.
Then Jack helped solve the problem.
I used to put the last mile in my previous solution. I didn't know the csrf principle of Django, So I went blind there, wasting a lot of time.
Next, let me talk about the problem. If you and I make the same mistake, you can make a reference.
First, I made test.html, as follows:
<! Doctype> <HTML lang = "ZH-CN">
The access time is xx.xx.com/post, and the execution region is
def post_html(rq):return render_to_response("test.html")
This form already contains TAG {% csrf_token %}. This is the tag that needs to be added in the online solution.
Click the publish button to submit the form and execute the/postblog operation. Next, let's take a look at the server code.
First add in settings. py
django.middleware.csrf.CsrfViewMiddleware
MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', # Uncomment the next line for simple clickjacking protection: # 'django.middleware.clickjacking.XFrameOptionsMiddleware',)
See URLs. py again
url(r'^postblog$','postBlog')
View views. py
def postBlog(rq):return render_to_response('ok.html', context_instance=RequestContext(rq))
For a Django beginner, everything is done according to the help on the error page. Why is the result still wrong?
A: Because, from the very beginning, the HTML page is wrong, and I am trying to remedy the problem on the premise of the error, so I cannot save it.
Experienced Django developers should see the root cause of the error at a glance.
In fact, {% csrf_token %} in the form has been assigned a value when the HTML page is loaded, and the assigned csrf_token needs to be sent to the server for verification during post, if the verification is successful, the post operation can be performed. Otherwise, it is considered a csrf attack.
In the above text, test.html does not initially provide a csrf_token by the server, so it cannot be successfully verified during post.
Context_instance = requestcontext (RQ) is used to assign values to the csrf_token, but the assignment operation is carried out after post in the above text, the correct operation is to assign a value when the HTML page is opened before post.
You only need to modify the post_html method:
def post_html(rq):return render_to_response("test.html",context_instance=RequestContext(rq))
Above.