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
First make sure you have SessionMiddleware and AuthenticationMiddleware middlewares added to your MIDDLEWARE_CLASSES setting. request. user will give you a User object representing the currently logged-in user. If a user isn't currently logged in, request.
Method 3 – get_user_model() : The other way to reference the user model is via get_user_model which returns the currently active user model: either a custom user model specificed in AUTH_USER_MODEL or else the default built-in User. Inside the models.py add the following code: Python3.
Django will create or use an autoincrement column named id by default, which is the same as your legacy column.
UUID, Universal Unique Identifier, is a python library that helps in generating random objects of 128 bits as ids. It provides the uniqueness as it generates ids on the basis of time, Computer hardware (MAC etc.). Universally unique identifiers are a good alternative to AutoField for primary_key .
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With