I am trying to post a form from Extjs to Django (ver 3.1) as backend and have an CSRF token Error from the Django side "POST /test/ HTTP/1.1" 403"
My senerio is this :
My Extjs app run on localhost:1841 (default from extjs for development)
My Django app run on localhost:8000 (defualt Django runserver command...)
Both on the same server.
I did read that because I am not generating the form from Django but from the ExtJS which is external to django , I need to get the CSRF through Django api ==> get_token(request)...
so here is my view :
def csrf(request):
return JsonResponse({'csrftoken': get_token(request)})
Here is the JS function that call this csrf function...
function getCsrfToken () {
Ext.Ajax.request ({
url : 'http://127.0.0.1:8000/csrf/',
success : function (response, opts) {
obj = Ext.decode (response.responseText, true);
#save it for later user...
Ext.util.Cookies.set('csrftoken', obj['csrftoken']);
},
})
};
I did test it , and it is working fine by generating CSRF token.
Here is my submit form action (POST) from the ExtJs side...
onSubmitClick : function () {
let form = Ext.getCmp ('formID');
var csrf = Ext.util.Cookies.get ('csrftoken');
if (form.isValid ())
form.submit ({
url : 'http://127.0.0.1:8000/test/',
headers : {
'X-CSRFToken': csrf,
},
success : function (form, action) {
let data = Ext.decode (action.response.responseText)
Ext.Msg.alert ('Success', data['success']);
},
});
} else { // display error alert if the data is invalid
Ext.Msg.alert ('Invalid Data', 'Please correct form errors.')
}
}
As you can see , I did send the CSRF token from the in the header...
headers : {
'X-CSRFToken': csrf,
},
After that I did get the Django CSRF Error as shown above.
Here is my Django relevant setting...
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'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',
]
ROOT_URLCONF = 'core.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'templates'),
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'core.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
# corsheaders
CORS_ORIGIN_ALLOW_ALL = True
#CSRF
CSRF_HEADER_NAME = 'X-CSRFToken'
CSRF_COOKIE_SECURE = False
#CSRF_USE_SESSIONS = True
CORS_ALLOW_CREDENTIALS = True
#CORS_ORIGIN_WHITELIST = ['127.0.0.1:8000']
CSRF_TRUSTED_ORIGINS = ['localhost:1841']
Here is the image of the get request for getting the token ...
Here is the image log of the Post Request...
Any Help With this error please.
Thanks for your replies!