Forbidden (CSRF token missing or incorrect.)

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

HTML page:

<b>All Posts</br></b>
    {% 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>
                <input type="submit" value = "Post" id="SubmitPost">
    <!--. Add new post form ends -->
    </div class="Container" name="Container" id="Container">
    {% block script %}
    <script src="{% static 'network/jsindex.js' %}" defer>
    {% endblock %}

    {% endif %}
{% endblock %}

JS file:

    x = document.querySelector('textarea').value
    fetch('/posts', {
        method: 'POST',

        body: JSON.stringify({
            pcontent: x,
      .then(response => response.json())
      .then(result => {
        // Print 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!