Django Version: 1.11.15
Error reported for post request in django:
Forbidden (403)
CSRF verification failed. Request aborted.
Help
Reason given for failure:
CSRF cookie not set.
Method 1: Do not use CSRF authentication</strong
Disable sitewide (not recommended)
Remove the django.middleware.csrf.CsrfViewMiddleware middleware from MIDDLEWARE in settings.py
For example, the following configuration would remove the django.middleware.csrf.CsrfViewMiddleware
MIDDLEWARE = [
‘django.middleware.security.SecurityMiddleware’,
‘django.contrib.sessions.middleware.SessionMiddleware’,
‘django.middleware.common.CommonMiddleware’,
‘django.middleware.csrf.CsrfViewMiddleware’,
‘django.contrib.auth.middleware.AuthenticationMiddleware’,
‘django.contrib.messages.middleware.MessageMiddleware’,
‘django.middleware.clickjacking.XFrameOptionsMiddleware’,
]
Partially disabled (recommended)
Or you can add @csrf_exempt for views where you don’t want csrf protection
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def ajaxGetList(r):
Method 2: Use CSRF validation</strong
form form to add
{% csrf_token %}
views.py code
from django.template.context_processors import csrf
from django.http import HttpResponse
from django.template import Context, loader
def my_view(request):
c = {}
c.update(csrf(request))
# … view code here
return HttpResponse(loader.get_template(‘index.html’).render(c))
Older versions of the code.
from django.core.context_processors import csrf
from django.shortcuts import render_to_response
def my_view(request):
c = {}
c.update(csrf(request))
# … view code here
return render_to_response(“a_template.html”, c)
js code
Add a header of X_CSRFTOKEN when sending an ajax POST request
// using jQuery
var csrftoken = jQuery(“[name=csrfmiddlewaretoken]”).val();
or
var csrftoken = $.cookie(‘csrftoken’);
Code 1:
function submitForm(){
var user = $(‘#user’).val();
$.ajax({
url: ‘/csrf1.html’,
type: ‘POST’,
headers:{‘X-CSRFToken’: csrftoken},
data: { “user”:user},
success:function(arg){
console.log(arg);
}
})
}
Code 2.
// Go to the cookie to get the value
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader(“X-CSRFToken”, csrftoken);
}
}
});
function DoAjax(){
$.ajax({
url: ‘/csrf/’,
type: ‘POST’,
data: {‘k1’: ‘v1’},
success: function (data) {
console.log(data);
}
})
}
PS:
1.csrf decorator
Global.
Middleware django.middleware.csrf.CsrfViewMiddleware
Local.
from django.views.decorators.csrf import csrf_exempt,csrf_protect
@csrf_protect, enforce anti-cross-site request forgery for the current function, even if no global middleware is set in settings.
@csrf_exempt, disables cross-site request forgery prevention for the current function, even if the global middleware is set in settings.
2. django recommends using django.middleware.csrf.CsrfViewMiddleware for global control, and does not advocate using @csrf_protect for single-view control, as this may be missed. You can add @csrf_exempt if you don’t want csrf-protected views. Use CSRF authentication: add django.core.context_processors.csrf to the TEMPLATE_CONTEXT_PROCESSORS of the configuration file, or manually generate csrftoken and add it to the template context.
3. django 1.11 csrf official documentation: https://docs.djangoproject.com/en/1.11/ref/csrf/#django.views.decorators.csrf.csrf_protect
Similar Posts:
- Error encountered in Django: forbidden CSRF cookie not set
- Django @csrf_exempt Cannot work in class view (Django @csrf_exempt not working in class View)
- “No module named context_processors”
- ERRORS: ?: (corsheaders.E013) Origin ‘*’ in CORS_ORIGIN_WHITELIST is missing scheme or ne…
- [Solved] Forbidden (403) CSRF verification failed. Request aborted.
- Django admin Error: ‘WSGIRequest’ object has no attribute ‘user’
- Forbidden (CSRF token missing or incorrect.):
- How to Solve Django xadmin installation Error [7 Types of Errors]
- When deploying Django project on centos7, there will be an error of importerror: cannot import name middlewaremin
- Django logs detailed error reporting information