skip to Main Content

I have already checked this link on Stackoverflow but still facing same issue: CSRF verification failed. Request aborted. on django

About the issue

I am trying to submit ajax request to DJango.

Html Form

<form id="frmLogin" method="post">
    {% csrf_token %}
    <input type="text" name="username" />
    <input type="password" autocomplete="false" name="password" />
    <input type="submit" value="Submit" />
</form>

Ajax

$("form#frmLogin").validate({
    rules: {
        username: {
            required: true
        },
        password: {
            required: true
        }
    },
    submitHandler: function(form) {
        var data = {
            "username": $(form).find("input[name='username']").val(),
            "password": $(form).find("input[name='password']").val(),
            "csrfmiddlewaretoken": $(form).find("input[name='csrfmiddlewaretoken']").val()
        };      
        $.ajax({
            method: "POST",
            url: "/authenticate/",
            cache: false,
            async: true,
            data: JSON.stringify(data),
            contentType: "application/json; charset=utf-8",
            success: function(response) {                   
                //$(form).remove();
            }
        })
    }
});

View

from django.shortcuts import render
import json
from django.http import JsonResponse

def Authenticate(request):
    if request.method == "POST":
        #loginData = json.loads(request.body)
        #email = userData["email"]
        #password = userData["password"]
        print("ok")
        return JsonResponse({}, status = 200)
    else:
        print("not ok")

Payload Info

enter image description here

Error Message

enter image description here

enter image description here

Am I missing anything?

2

Answers


  1. Chosen as BEST ANSWER

    Following block need to be passed to add headers to make POST request successful.

    beforeSend: function(xhr, opts) {
        xhr.setRequestHeader('X-CSRFToken', $(form).find("input[name='csrfmiddlewaretoken']").val());
    }
    

  2. You need to add CSRF_TRUSTED_ORIGINS in settings.py file and add your origin to it as a trusted origin for unsafe requests like (POST request ) like this :

    CSRF_TRUSTED_ORIGINS = ['https://your-domain.com']
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search