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