Forbidden (403) CSRF verification failed. Request aborted


can you help me correct this error?

Easy and not recommended fix. Add csrf_exempt decorator to your view. Something like this if you are using function based views:

from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
@csrf_exempt
def my_view(request):
    return HttpResponse("I have opened my view up to cross site request forgery, yippee!")

I’m assuming you simply are using a form to login (based on url) and simply forgot to include {% csrf_protect %} template tag. This will most likely fix your issue without opening yourself up to cross-site scripting attacks.

    <form method="POST" action="">
        {% csrf_exempt %}
        {{ form }}
        <button type="Submit">Safely Submit</button>
    </form>

If you are using an Ajax based view as in Vitor’s ajax tutorial to check for username availability… the answer is a little bit more complicated but not too bad. You will need to use the getCookie function from the documentation and pass it to the ajax request as follows:

//returns cookie from browser- from Django docs link below
function getCookie(name) {
  var cookieValue = null;
  if (document.cookie && document.cookie !== '') {
      var cookies = document.cookie.split('console.log(data);;');
      for (var i = 0; i < cookies.length; i++) {
          var cookie = cookies[i].trim();
          // Does this cookie string begin with the name we want?
          if (cookie.substring(0, name.length + 1) === (name + '=')) {
              cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
              break;
          }
      }
  }
  return cookieValue;
}
//also from docs-
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);
        }
    }
});
var csrftoken = getCookie('csrftoken');
//set csrf token
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
    }
  }
});
//now your ajax logic as usual

https://docs.djangoproject.com/en/3.0/ref/csrf/

Lastly, I once had an issue where getCookie was not working for a user. In this case, do notice that Django adds an extra input field with type=“hidden” to all forms. The csrf_token is kept under the value attribute for this tag.

Something like this is another way to get csrf_token from form (jQuery):

$("form#my-id").click(function(e){
    //prevent form submit
    e.preventDefault();
    var csrf = $(this).find('input[name="csrfmiddlewaretoken"]').attr('value');
    //attach to $.ajaxSetup as seen in previous example
});