Python Django framework implements custom form submission, pythondjango

Source: Internet
Author: User

Python Django framework implements custom form submission, pythondjango

In addition to using Django built-in forms, we often need to customize forms. When submitting a custom form in Post mode, errors are often generated by CSRF (Cross-Site Request Forgery )."CSRF verification failed. Request aborted ."

This article focuses on "form submission" and "Ajax submission" to solve the errors caused by CSRF.

I. Form submission
Template:

<! DOCTYPE html> 

Views. py:

def Calculate(request):  if request.POST:    a=request.POST["ValueA"]    b=request.POST["ValueB"]    c=str(int(a)+int(b))    return render_to_response('Result.html',{'result':c})  else:    return render_to_response('Calculation.html',context_instance=RequestContext(request))

Note:

(1) Add {% csrf_token %} to the <form> label. In this way, the "csrfmiddlewaretoken" identifier will be generated during form submission to prevent CSRF

(2) On the Get request page, you need to add context_instance = RequestContext (request), which is used with {% csrf_token %}. If one is missing, the above error will occur. RequestContext must be in django. shortcuts Import

(3) The CSRF must be verified only when the form is submitted in Post mode. The Get method is not required.

Ii. Ajax submission
Compared with form submission, Ajax submission requires additional operations. When Ajax is submitted, you must provide the "csrfmiddlewaretoken" parameter. In addition to JQuery, we also need to introduce a piece of JS Code.

jQuery(document).ajaxSend(function(event, xhr, settings) {  function getCookie(name) {    var cookieValue = null;    if (document.cookie && document.cookie != '') {      var cookies = document.cookie.split(';');      for (var i = 0; i < cookies.length; i++) {        var cookie = jQuery.trim(cookies[i]);        // Does this cookie string begin with the name we want?        if (cookie.substring(0, name.length + 1) == (name + '=')) {          cookieValue = decodeURIComponent(cookie.substring(name.length + 1));          break;        }      }    }    return cookieValue;  }  function sameOrigin(url) {    // url could be relative or scheme relative or absolute    var host = document.location.host; // host + port    var protocol = document.location.protocol;    var sr_origin = '//' + host;    var origin = protocol + sr_origin;    // Allow absolute or scheme relative URLs to same origin    return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||      (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||      // or any other URL that isn't scheme relative or absolute i.e relative.      !(/^(\/\/|http:|https:).*/.test(url));  }  function safeMethod(method) {    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));  }   if (!safeMethod(settings.type) && sameOrigin(settings.url)) {    xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));  }});

Template:

<! DOCTYPE html> 

View. py:

def AjaxRequest(request):  if request.POST:    a =request.POST["a"]    b=request.POST["b"]    c=int(a)+int(b)    return JsonResponse(c,safe=False)  else:    return render_to_response('AjaxDemo.html',context_instance=RequestContext(request))

Note:

(1) After using the introduced JS Code, you need to add the following code so that JS can automatically generate the "csrfmiddlewaretoken" identifier for us. Then you can use $. post ().

$.ajaxSetup({          data:{csrfmiddlewaretoken: '{{ csrf_token }}'}        });

(2) context_instance = RequestContext (request) is not required

(3) You can directly use $. Get () for get requests without the preceding operations.
Note: This document uses Django1.8.3 for testing.

The above is all the content of this article, hoping to help you learn.

Articles you may be interested in:
  • Use the Python urllib library to submit WEB forms
  • Tutorial on web forms in the Python Flask framework
  • Example of form processing in the Django framework of Python
  • A simple way to improve forms in Django
  • Simple parsing of Form Verification in Django framework
  • Tutorial on Writing Contact forms in Django framework
  • Python implements simulated logon and form submission

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.