我试图在单击按钮时用Javascript创建请求,但收到错误Forbidden (CSRF token missing or incorrect.)
。我在HTML模板中包含了{% csrf_token %}
:
<form action="/cart" method="POST">
{% csrf_token %}
<button type="button" id="ordered">Place Order</button>
</form>
但是不确定是否必须将其包含在Javascript请求中:
const request = new XMLHttpRequest();
request.open("POST", "/cart");
// send request
let data = new FormData();
items = localStorage.getItem(user + "items")
total = localStorage.getItem(user + "price")
data.append("items", items)
data.append("total", total)
request.send(data);
在我的views.py
中:
def cart(request):
if request.method == "POST":
data = request.get_json()
print(f"{data}")
return HttpResponseRedirect(reverse("index"))
else:
return render(request, "cart.html")
您必须在每个JavaScript请求中发送CSRF令牌:https://docs.djangoproject.com/en/2.2/ref/csrf/#ajax