[Django]-Django– Deactivate User account instead of deleting it

17👍

You should show the code that didn’t work. From your description though, you’re doing a few things wrong.

First, .filter() always returns a queryset, not an instance. To get an instance, you should use .get().

Secondly, User is the class; the instance is user.

Thirdly, you have no reason to do a query here at all. request.user is already the User instance. There is no need to take that user, get its profile, ask the profile for the user ID, then do another query to get back the user you started with. Just use the user you already have.

Finally, never, ever do a blank except, as that will catch all sorts of unexpected errors and hide anything that could be going wrong. Only catch exceptions you actually know how to deal with. In this case, there is nothing specific you need to handle; if anything unexpected goes wrong, let Django report that error normally.

def delete_profile(request):
    user = request.user
    user.is_active = False
    user.save()
    messages.success(request, 'Profile successfully disabled.')
    return redirect('index')

3👍

You may need to set user.is_active = False and then save the user object.

def delete_profile(request):        
    user = request.user
    user.is_active = False
    user.save()
    logout(request)
    messages.success(request, 'Profile successfully disabled.')
    return redirect('index')

1👍

You need to save it too:

user.is_active = False
user.save()

0👍

After calling user.is_active = False you need to write the changes to the database by calling user.save()

Leave a comment