繁体   English   中英

如何修复 MultiValueDictKeyError

[英]How to fix a MultiValueDictKeyError

我正在尝试使用 Javascript 获取在 Django 项目中每个页面上花费的时间。 我不断收到错误,所以我正在尝试修复它

错误:

MultiValueDictKeyError at /backendurl/
'timeSpent'

views.py 中突出显示的错误行:

    timeSpent = request.POST['timeSpent']

这是模板中的javascript:

<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>

这是views.py:

def my_view_function(request):
    timeSpent = request.POST['timeSpent']
    response = json.dumps({
        'timeSpent' : timeSpent,
    })
    return HttpResponse(response)

这是 url.py

    path('backendurl/', views.my_view_function, name='backendurl'),

很可能,key 'timeSpent'不存在于request.POST

要从request.POST dict 中获取键的值,您需要使用MultiValuedDict 的 get 方法

您还可以设置一个默认值来知道您没有在请求中获得密钥,在下面的这种情况下为 -1。

timeSpent = request.POST.get('timeSpent', -1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM