Hello,
I have an increment function in views.py that sends and receives data. At each data reception it increments a value and when this value reaches a threshold it redirects to a page, page2.html
I have the request indicating that it accesses page2 but nothing happens. I always stay on page 1
goToPage2
"POST incremente HTTP/1.1" 302 0
"GET page2 HTTP/1.1" 200 1395
views.py
from django.http import JsonResponse
def page1(request):
# load and init data
request.session["nb"] = 0
context={"nb": 0}
return render(request, 'page1.html',)
def incremente(request):
request.session["nb"] = request.session.get("nb") +1
if(request.session.get("nb") < 5):
return JsonResponse({"nb": request.session.get("nb")})
else:
print("goToPage2")
return redirect("p2")
def page2(request):
return render(request, "page2.html")
page1.html
<body>
<h1 id="title"> </h1>
<form id="myForm" method="POST">
{% csrf_token %}
<button id="submit" type="submit">Valider</button>
</form>
<script type="text/javascript">
document.getElementById("title").textContent = "{{nb}}"
const form = document.getElementById('myForm')
form.addEventListener('submit', sendData);
function sendData(event){
event.preventDefault();
const csrf = $('input[name="csrfmiddlewaretoken"]').val()
$.ajax({
type: "POST",
url: 'incremente', //
data: { csrfmiddlewaretoken : csrf, "result": "data" },
dataType: "json",
success: function (data) {
document.getElementById("title").textContent = data["nb"] },
failure: function () {alert("failure");}
})
}
</script>
</body>
urls.py
from django.urls import path, re_path
from . import views
urlpatterns = [
path('page1', views.initQuiz, name="p1"),
re_path(r'^incremente
, views.incremente),
path('page2',views.page2,name="p2"),
]