我无法从django模型,django.contrib.auth.models.User获取用户,如id ...我想删除用户,所以我试图找到它像的是:
User.objects.get(id=request.POST['id'])
但它不起作用,并返回
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用户实例的删除方法?
感谢
答案 0 :(得分:12)
这就是这样做的方法,问题在于您所请求的用户不存在。如果您想处理这种情况,请使用:
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
。