PythonDjango framework implements custom form submission-Python tutorial

Source: Internet
Author: User
This article mainly introduces the Django framework to implement custom form submission. for & quot; form submission & quot; and & quot; Ajax submission & quot; these two methods are used to solve the errors caused by CSRF. if you are interested, you can refer to the following: in addition to using Django built-in forms, sometimes we 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:

  
   Calculate numbers and  

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) in

Add {% csrf_token %} to the tag. During form submission, the "csrfmiddlewaretoken" identifier will be generated 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:

  
    Ajax 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.