Hi,
I am trying to get the time spent on each page in a django project using Javascript. I keep getting an error so I am trying to fix it
the error:
MultiValueDictKeyError at /backendurl/
'timeSpent'
Highlighted line of error in views.py:
timeSpent = request.POST['timeSpent']
Here is the javascript in template:
<script>
$(document).ready(function() {
var startDate = new Date();
$(window).unload(function() {
var endDate = new Date();
$.ajax({
type: POST,
url: "backendurl", // be mindful of url names
data: {
'timeSpent': endDate - startDate || 'none' // defaults to a string
},
success: function(response) {
// unpack response:
status = response.status
}
})
</script>
Here is the views.py:
def my_view_function(request):
timeSpent = request.POST['timeSpent']
response = json.dumps({
'timeSpent' : timeSpent,
})
return HttpResponse(response)
Here is the url.py
path('backendurl/', views.my_view_function, name='backendurl'),