본문 바로가기

Django

Django csft token with Ajax

반응형

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

 

Cross Site Request Forgery protection | Django documentation | Django

Django The web framework for perfectionists with deadlines. Overview Download Documentation News Community Code Issues About ♥ Donate

docs.djangoproject.com

폼을 이용하는 경우 

  • 폼 tag 사이에 {% csft_token %} 을 넣어주면 된다.
<form action="{% url 'post-detail-edit' %}" method="post">
    {% csrf_token %}
</form>

 

Ajax를 이용하는 경우

  • javascript로 csrftoken 값을 가져와서 X-CSRFToken 값으로 ajax object의 header에 넣어준다.
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const 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;
}
function addComment(){
    let oAjaxReq = new XMLHttpRequest();
    oAjaxReq.open("POST", "/add_comment");
    let comment = document.getElementById("commentTextArea").value;
    let post_id = document.getElementById("post_id").value;

    let formData = new FormData();
    formData.append('post_id', post_id);
    formData.append('comment', comment);

    oAjaxReq.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));

    oAjaxReq.send(formData);
    oAjaxReq.onload = function (){
        console.log(oAjaxReq.response);
        let insertedComment = document.createElement("span");
        insertedComment.innerHTML = comment;
        let editButtonDiv = document.getElementById("editButtonDiv");
        editButtonDiv.parentNode.insertBefore(insertedComment, editButtonDiv.nextSibling);
    }
}
반응형