Reputation: 772
I cant'figure it out how to get a User, from the django model, django.contrib.auth.models.User, by id... I want to delete a user so I'm trying to find it like that:
User.objects.get(id=request.POST['id'])
But it doesn work, and returns
User matching query does not exist.
the id is sent by 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;
});
I debug it and it's ok, the user exists in the DB and the id is correct
How do I do that? Is there any delete method for django User instances?
thanks
Upvotes: 15
Views: 32288
Reputation: 22697
That is the way to do it, the problem here, is that your requested user does not exist. If you want to handle this case, use this:
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.
Also, you need transform your id to Int
.
Upvotes: 27