Django has encountered a 403 error submitting form: CSRF verification failed

Source: Internet
Author: User

When learning the Django Framework submission form, 403 errors were encountered, as follows:

Forbidden (403) CSRF verification failed.
Request aborted. You are are seeing this message because this site requires a CSRF cookies when submitting forms.
This cookies are required for the security reasons, to ensure that your browser isn't being hijacked by third parties. If you are have configured your browser to disable cookies, please re-enable them, at least for this site, or for ' Same-origin
' Requests.
Help Reason given for failure:     CSRF cookies not set.      In general, this can occur when there be a genuine Cross Site Request forgery, or when Django ' s CSRF m Echanism has not been used correctly.
For POST forms, your need to ensure:1. Your Browser is accepting cookies.
2. The view function passes a request to the template ' s Render method.
3. In the template, there are a {% Csrf_token%} template tag inside each POST form this targets an internal URL. 4. If you are is not a using csrfviewmiddleware, then you must use Csrf_protect on the "any" and "use" Csrf_tokenAte tag, as as, as those that accept the POST data. 5. The form has a valid CSRF token.  After logging in in another browser tab or hitting the "back button" after a login, you could need to reload the page with the

 form, because the token is rotated after a login.
Follow the prompts to check again:

1. My browser is open cookies, no problem;

2. The code in my view.py is like this:

#coding =utf-8
from django.shortcuts import Render, Render_to_response

#表单
class UserForm (forms. Form):
    username = forms. Charfield (label= ' username ', max_length=20)
    password = forms. Charfield (label= ' password ', widget=forms. Passwordinput ())

def Register (Request):
    if Request.method = = ' POST ':
        uf = UserForm (Request. POST)
        if Uf.is_valid ():
            #获得表单数据
            username = uf.cleaned_data[' username ']
            password = uf.cleaned_data [' Password ']
            #添加到数据库
            User.objects.create (username= username,password=password) return
            HttpResponse (' Register success !!')
        else: Return
            httpresponse (' Register failed!! ')
    else:
        uf = UserForm () return
        render_to_response (' register.html ',  context=requestcontext (request, {' UF ': UF})

This code is copied from the Internet, and it does use the RequestContext, and the request is passed to RequestContext, as if there is no problem.

3. The contents of my template are as follows:

<?xml version= "1.0" encoding= "UTF-8"?> <!
DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 strict//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" >
"{% Csrf_token%}" is also true in the template, and it seems to be fine.

4. Middleware Csrfviewmiddleware in the project created by default joined, there is no problem.

5. The first time the form was submitted, there were 403 errors and there was no chance of a retreat, which could also be ignored.

And look at two extra points:

1. The background server prints the following log:

userwarning:a {% Csrf_token%} is used in A template and but the context did not provide the value. This is usually caused by not using RequestContext.

2. View your browser's cookies

I am using a Chrome browser that installs the plugin Web Developer and can see that the page does not have any cookies set up.


You can see that the cookie for the page is not set up successfully, and the cookie is set in the 2nd of the check list, the Django installed by this machine is version 1.10, and the copy of the code is run in the previous version of 1.10, guess it may be the method render_to_ Response caused by, instead of using the Render method:

def register (Request):
    if Request.method = = ' POST ':
        uf = UserForm (Request. POST)
        if Uf.is_valid ():
            #获得表单数据
            username = uf.cleaned_data[' username ']
            password = uf.cleaned_data[' Password ']
            #添加到数据库
            User.objects.create (username= username,password=password) return
            HttpResponse (' Register success!! ')
        else: Return
            httpresponse (' Register failed!! ')
    else:
        uf = UserForm () return
        render (request, ' register.html ', context ({' UF ': uf})
The results work, and the Web Developer lets you see that the cookie "Csrftoken" was successfully set by the page:




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.