1

The issue is encountered in the framework of Django. The related code lines are described below.

These are the HTML lines, in which, the first div and the nested p will be filled with other HTML elements through a JavaScript function; the mentioned JavaScript function is not brought here for the sake of brevity:

<form method="POST">
    {% csrf_token %}
    <div id="bill">
    </div>
    <div>
        <p id="total"></p>
    </div>
    <button onclick="record_order()">llllll</button>
</form>

Here is the JavaScript codes for the earlier record_order() used in button's onclick attribute in the HTML lines:

function record_order() {
    fetch("http://localhost:8000/", {
        method: "POST",
        body: JSON.stringify({
            "a": 1,
            "b": "vb"
        }),
        headers: {
            "Content-type": "application/json; charset=UTF-8",
        }
    })
    .then((response) => response.json())
    .then((json) => console.log(json));
}

Also, there is the class-based view whose post method is overridden like this:

def post(self, request):
        print("---")
        print(request.POST)
        print("---")
        return HttpResponseRedirect("/")

The button, when clicked, should call the JavaScript fetch() which will send the data to the server-side so it can be accessed via the request. But, the browser console logs out:

order.js:42
POST http://localhost:8000/ 403 (Forbidden)
record_order    @   order.js:42
onclick @   (index):1331

and

Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

On the other hand the terminal prints an error, the CSRF token, and not more:

---
Forbidden (CSRF token missing.): /
<QueryDict: {'csrfmiddlewaretoken': ['qD77PCO0L62oexifqwHWPT9WjB3SaRyau3SDlApCokLhCVcQb98wNOHCdBLNDDwk']}>
---

The problem is highly probable to be in the fetch part, however trying several HTTP headers didn't work out at all.

How is it possible to get the desired data in post() method of the view and save it to the SQLite database through Django models?

1
  • 2
    The problem is that your JavaScript function does not have the csrf token. There are several ways of getting it from your HTML. Check out the docs on Using CSRF protection with AJAX to see how to include the token in your JavaScript. Commented Mar 12 at 13:55

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.