Home > Software engineering >  Invalid CSRF or Missing Token in DJango
Invalid CSRF or Missing Token in DJango

Time:10-09

I have already checked this link on Stackoverflow but still facing same issue: enter image description here

Error Message

enter image description here

enter image description here

Am I missing anything?

CodePudding user response:

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']

CodePudding user response:

Try attaching your form to the ajax function like this:

    const form = document.getElementById('frmLogin');

    var data = {
        "username": $(form).find("input[name='username']").val(),
        "password": $(form).find("input[name='password']").val(),
        "csrfmiddlewaretoken": $(form).find("input[name='csrfmiddlewaretoken']").val()
    };

    $('#frmLogin').submit(function() {
        $.ajax({
            method: "POST",
            url: "/authenticate/",
            cache: false,
            async: true,
            data: JSON.stringify(data),
            contentType: "application/json; charset=utf-8",
            success: function(response) {

            }
        })
    })

  • Related