Django form post has two solutions: CSRF verification failed (CSRF verification failed)

Source: Internet
Author: User
Tags form post

Django form post has two solutions: CSRF verification failed (CSRF verification failed)
Symptom

The form interface is as follows:


After clicking submit, the following error page appears:



The HTML code is as follows:

Contact_form.html

<!DOCTYPE HTML PUBLIC >

The view code is as follows:

View. py

# -*- coding: utf-8 -*-from django.core.mail import send_mailfrom django.http import HttpResponseRedirectfrom django.shortcuts import render_to_responsedef contact(request):    errors = []    if request.method == 'POST':        if not request.POST.get('subject', ''):            errors.append('Enter a subject.')        if not request.POST.get('message', ''):            errors.append('Enter a message.')        if request.POST.get('email') and '@' not in request.POST['email']:            errors.append('Enter a valid e‐mail address.')        if not errors:            send_mail(                      request.POST['subject'],                      request.POST['message'],                      request.POST.get('email', 'noreply@example.com'),                      ['siteowner@example.com'],                      )            return HttpResponseRedirect('/contact/thanks/')    return render_to_response('contact_form.html', {                                                    'errors': errors,                                                    'subject': request.POST.get('subject', ''),                                                    'message': request.POST.get('message', ''),                                                    'email': request.POST.get('email', ''),                                                    })

Generally, cookies are enabled in browsers. Therefore, in the error information shown in the figure above, we will focus on the last three points and make changes as prompted:

Solution 1: CSRF verification settings

1. In view. py's render_to_response, use RequestContext to replace the default Context.

View. py

# -*- coding: utf-8 -*-from django.core.mail import send_mailfrom django.http import HttpResponseRedirectfrom django.shortcuts import render_to_responsefrom django.template import RequestContextdef contact(request):    errors = []    if request.method == 'POST':        if not request.POST.get('subject', ''):            errors.append('Enter a subject.')        if not request.POST.get('message', ''):            errors.append('Enter a message.')        if request.POST.get('email') and '@' not in request.POST['email']:            errors.append('Enter a valid e‐mail address.')        if not errors:            send_mail(                      request.POST['subject'],                      request.POST['message'],                      request.POST.get('email', 'noreply@example.com'),                      ['siteowner@example.com'],                      )            return HttpResponseRedirect('/contact/thanks/')    return render_to_response('contact_form.html', {                                                    'errors': errors,                                                    'subject': request.POST.get('subject', ''),                                                    'message': request.POST.get('message', ''),                                                    'email': request.POST.get('email', ''),                                                    },context_instance=RequestContext(request))

2. Add {% csrf_token %} to the form in the template file }.

Contact_form.html

<!DOCTYPE HTML PUBLIC >

Test Run, successful!

PS: article 4 of the error message in the image above. when setting up the django project, setting. py has automatically added 'django. middleware. csrf. CsrfViewMiddleware ',

MIDDLEWARE_CLASSES = (    'django.contrib.sessions.middleware.SessionMiddleware',    'django.middleware.common.CommonMiddleware',    'django.middleware.csrf.CsrfViewMiddleware',    'django.contrib.auth.middleware.AuthenticationMiddleware',    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',    'django.contrib.messages.middleware.MessageMiddleware',    'django.middleware.clickjacking.XFrameOptionsMiddleware',    'django.middleware.security.SecurityMiddleware',    'django.middleware.locale.LocaleMiddleware',)



Solution 2: Do not use CSRF Verification

1. Delete 'django. middleware. csrf. CsrfViewMiddleware 'in the setting. py file, as shown below:

MIDDLEWARE_CLASSES = (    'django.contrib.sessions.middleware.SessionMiddleware',    'django.middleware.common.CommonMiddleware',    #'django.middleware.csrf.CsrfViewMiddleware',    'django.contrib.auth.middleware.AuthenticationMiddleware',    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',    'django.contrib.messages.middleware.MessageMiddleware',    'django.middleware.clickjacking.XFrameOptionsMiddleware',    'django.middleware.security.SecurityMiddleware',    'django.middleware.locale.LocaleMiddleware',)

2. Remove the {% csrf_token %} mark from the form. As follows:

Contact_form.html

<!DOCTYPE HTML PUBLIC >

3. In view. py's render_to_response, RequestContext is not used. As follows:

View. py

# -*- coding: utf-8 -*-from django.core.mail import send_mailfrom django.http import HttpResponseRedirectfrom django.shortcuts import render_to_responsefrom django.template import RequestContextdef contact(request):    errors = []    if request.method == 'POST':        if not request.POST.get('subject', ''):            errors.append('Enter a subject.')        if not request.POST.get('message', ''):            errors.append('Enter a message.')        if request.POST.get('email') and '@' not in request.POST['email']:            errors.append('Enter a valid e‐mail address.')        if not errors:            send_mail(                      request.POST['subject'],                      request.POST['message'],                      request.POST.get('email', 'noreply@example.com'),                      ['siteowner@example.com'],                      )            return HttpResponseRedirect('/contact/thanks/')    return render_to_response('contact_form.html', {                                                    'errors': errors,                                                    'subject': request.POST.get('subject', ''),                                                    'message': request.POST.get('message', ''),                                                    'email': request.POST.get('email', ''),                                                    })

Run again. The test is successful!





Urgent: when Firefox is used, CSRF verification failed Request aborted

When Firefox was used, it was forbidden (403 ). CSRF Verification Failed. Request aborted. Cause of failure: CSRF cookies are not set. In general, this can happen when there is a real cross-site request forgery, or when Django's CSRF mechanism is not properly used. For the POST form, make sure that: * this view function uses the template RequestContext instead of out-of-band. * The template contains 1% csrf_token %) (the template URL is marked as an internal target in the form of a post office. * If you do not use CsrfViewMiddleware, you must use the data csrf_protect for any comments, use the csrf_token template tag, and accept the positions. You can see the help section on this page, because you are debugging = true settings file in your Django. If this condition is changed to False, only the initial error information is displayed. You can customize the settings on this page using CSRF_FAILURE_VIEW

This is a bit of a problem. If you restart it, I used Firefox. I am using google Now, mainly because the Firefox agent is very troublesome. I am going to go to youtube, but I am not comfortable with google now. However, please help me. I want to ask a question. Baidu says I have nothing to offer and I don't have a reward. I have to wait for a few days and no one will answer it. Please...

Forbidden (403) CSRF verification failed Request aborted

You can click "Download Ubuntu" on the right of the webpage. Remember to give it a score.




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.