Django,如何使用 django.contrib.auth.models.User 通过 id 获取用户

Django, how to get a user by id, using the django.contrib.auth.models.User

我不知道如何通过 id 从 django 模型 django.contrib.auth.models.User 获取用户...我想删除一个用户,所以我试图这样找到它:

 User.objects.get(id=request.POST['id'])

但它不起作用,并且returns

User matching query does not exist.

id由ajax发送:

 $("#dynamic-table").on('click','.member_delete_btn', function() {
        if (confirm("Are you sure? the member will be deleted...") == true) {
            $.ajax({
                type: "POST",
                url: "/panel/member/delete/",
                data: { id: $(this).attr('data-id'), 'csrfmiddlewaretoken': '{{ csrf_token }}' },
                success: function (data) {
                     if(data.success) {
                         $('#result').html('<div class="alert alert-success"> <strong>Well done!</strong> Member deleted.</div>');
                         list_members();
                     }else{
                         $('#result').html('<div class="alert alert-warning"> <strong>Warning!</strong> Member not deleted.</div>');
                     }
                },
                error: function (data) {
                    alert("failure:" + data.error);
                }
            });
        }
        else {
            return false;
        }
        return false;
    });

调试没问题,数据库中存在用户,id正确

我该怎么做? django User 实例有删除方法吗?

谢谢

就是这样,这里的问题是您请求的用户不存在。如果你想处理这种情况,使用这个:

try:
   user_id = int(request.POST['id'])
   user = User.objects.get(id=user_id)
except  User.DoesNotExist:
   //handle the case when the user does not exist. 

此外,您需要将您的 id 转换为 Int