Orm forms using csrf
a. Basic applications
form form to add
{% csrf_token %}
b. Site-wide disabling
# '',
c. Partial disablement
'', from import csrf_exempt @csrf_exempt def csrf1(request): if == 'GET': return render(request,'') else: return HttpResponse('ok')
d. Localized use
# '', from import csrf_exempt,csrf_protect @csrf_protect def csrf1(request): if == 'GET': return render(request,'') else: return HttpResponse('ok')
ajax submit data
Ajax submits data with CSRF:
a. Place in data to carry
<form method="POST" action="/"> {% csrf_token %} <input type="text" name="user" /> <input type="submit" value="Submit"/> <a onclick="submitForm();">Ajaxsubmit (a report etc)</a> </form> <script src="/static/jquery-1.12."></script> <script> function submitForm(){ var csrf = $('input[name="csrfmiddlewaretoken"]').val(); var user = $('#user').val(); $.ajax({ url: '/', type: 'POST', data: { "user":user,'csrfmiddlewaretoken': csrf}, success:function(arg){ (arg); } }) } </script>
b. Placement in request header
<form method="POST" action="/"> {% csrf_token %} <input type="text" name="user" /> <input type="submit" value="Submit"/> <a onclick="submitForm();">Ajaxsubmit (a report etc)</a> </form> <script src="/static/jquery-1.12."></script> <script src="/static/"></script> <script> function submitForm(){ var token = $.cookie('csrftoken'); var user = $('#user').val(); $.ajax({ url: '/', type: 'POST', headers:{'X-CSRFToken': token}, data: { "user":user}, success:function(arg){ (arg); } }) } </script>
Additional knowledge:Adding authenticated csrfmiddlewaretoken to django form and ajax submissions
1. For ajax submit data, add the following code to the head of the js, you can ensure that ajax execution automatically submit the parameter csrfmiddlewaretoken.
$.ajaxSetup({data: {csrfmiddlewaretoken: '{{ csrf_token }}' }});
2. For a form to submit data, add the {% csrf_token %} tag inside the form, which will automatically generate an input tag.
<form>{% csrf_token %}</form>
capture
<form><input name="csrfmiddlewaretoken" value="..." type="hidden"></form>
Or add it using js:
$("#csrf_token").replaceWith("{% csrf_token %}");
3. Also document the use of template filters for processing.
$("#{{ }}").replaceWith('{{ field|linebreaksbr }}'); $(".{{ }}").text('{{ |striptags }}'); {{ value|linebreaksbr }}: "Joel\nis a slug" => "Joel<br>is a slug" {{ value|striptags }}: "<b>Joel</b> <button>is</button> a <span>slug</span>" => "Joel is a slug".
Above this django-csrf use and disable the way is all I share with you, I hope to give you a reference, and I hope you support me more.