Python Django Framework enables custom form submissions

Source: Internet
Author: User
In addition to using Django built-in forms, sometimes we often need to customize the form. Submitting a custom form post often leads to errors caused by CSRF (cross-site request forgery) "CSRF verification failed. Request aborted. "

This article focuses on "form submission" and "Ajax commit" two ways to solve the error caused by CSRF

One, 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))

Need to note:

(1) in

Add {% Csrf_token%} inside the tag so that the "Csrfmiddlewaretoken" flag is 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%}, the missing one will appear the above error, RequestContext need to Django.shortcuts Import

(3) It is only necessary to verify that the Csrf,get mode is not required when the form is submitted as post

Second, Ajax submissions
With the form submission, AJAX submissions require additional action, and Ajax commits need to provide the "Csrfmiddlewaretoken" identity parameters themselves. We need to introduce a JS code in addition to the introduction of jquery.

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 (Nam          E.length + 1));        Break  }}} return cookievalue; } function Sameorigin (URL) {//URL could be relative or scheme relative or absolute var host = Document.location.h Ost    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) = = or      Igin + '/') | | (url = = Sr_oRigin | |      Url.slice (0, sr_origin.length + 1) = = Sr_origin + '/') | |      Or any of the other URLs 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 Submissions              

The result of the calculation is:

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

Need to note:

(1) After the introduction of the JS code, you need to add the following code, so JS can automatically help us generate "Csrfmiddlewaretoken" logo, then you can use $.post ()

$.ajaxsetup ({          Data:{csrfmiddlewaretoken: ' {{csrf_token}} '}        });

(2) Context_instance=requestcontext (request) is not required

(3) Get requests do not require the above operation, directly using $.get () can be
Note: This article uses the Django1.8.3 version to test.

The above is the whole content of this article, I hope that everyone's study has helped.

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