Forbidden (CSRF token missing or incorrect.)

Getting error: Forbidden (CSRF token missing or incorrect.)

HTML page:

<b>All Posts</br></b>
    </br>
    {% if user.is_authenticated %}
    <div class="newPost">
    <div>New Post</div>
    <!--. Add new post form begins -->

        <form action="{% url 'index' %}" method="post" name="AddPost" id="postform">
            {% csrf_token %}
            
            <div >
                <textarea class="txtarea" name="txtarea" id="txtarea" placeholder="Body"></textarea>
            </div>
            <div>
                <input type="submit" value = "Post" id="SubmitPost">
            </div>
        </form>
    <!--. Add new post form ends -->
    </div>
    <div>
        <b>{{user}}</b>
    </div class="Container" name="Container" id="Container">
    <div>
     </div>
    {% block script %}
    <script src="{% static 'network/jsindex.js' %}" defer>
        </script>
    {% endblock %}

    {% endif %}
{% endblock %}

JS file:

document.addEventListener('submit',function(event){
    event.preventDefault();
    x = document.querySelector('textarea').value
    fetch('/posts', {
        method: 'POST',

        body: JSON.stringify({
            pcontent: x,
               })
      })
      .then(response => response.json())
      .then(result => {
        // Print result
          console.log(result);
      });
})

You need to make sure that the csrf token is included in your AJAX POST. See the AJAX docs for this.

1 Like

Thanks for the reply. I am not sure where exactly settings need to be changed.

It’s not a settings change, it’s a code change in the function doing the POST. You need to include the csrf_token in the data you’re submitting.

Thanks for the reply. I will try it.

I changed the code and it works. Thank you very much!