How to delete user in django?
Asked Answered
O

2

12

This may sounds a stupid question but I have difficulty deleting users in django using this view:

@staff_member_required 
def del_user(request, username):    
    try:
        u = User.objects.get(username = username)
        u.delete()
        messages.sucess(request, "The user is deleted")
    except:
      messages.error(request, "The user not found")    
    return render(request, 'front.html')

in urls.py I have

url(r'^del_user/(?P<username>[\w|\W.-]+)/$', 'profile.views.del_user'), 

Instead the user being deleted I get The user not found.

What can be wrong here?

Osugi answered 15/11, 2015 at 2:53 Comment(4)
Well you are goind into the except block, it is not a good idea use a generic except. You could try printing the error you're getting.Zumstein
Remove the try and except to look for any errors.Sapor
There's probably too little information here for us to help you, but one thing you might try is opening up a python console in your environment and manually run each step. I find that tends to illuminate a lot of issues. (just remember to do "from django import setup" and then "setup()" first if using Django 1.7+Sniper
Use try: yourcode... expect DoesNotExist: dosomething... instead.Vicenta
A
17

You should change your code to:

@staff_member_required 
def del_user(request, username):    
    try:
        u = User.objects.get(username = username)
        u.delete()
        messages.success(request, "The user is deleted")            

    except User.DoesNotExist:
        messages.error(request, "User doesnot exist")    
        return render(request, 'front.html')

    except Exception as e: 
        return render(request, 'front.html',{'err':e.message})

    return render(request, 'front.html') 

and display the err in your template to see further error messages

Albite answered 15/11, 2015 at 4:59 Comment(1)
I want a button for this, so when I click the button beside the User in a ListView of users, then it takes that users pk, so I can filter it.Moia
T
-5
@login_required
def del_user(request):
    user = request.user
    user.delete()
    redirect("login")

Talyah answered 19/9, 2023 at 4:7 Comment(2)
OP didn't want to delete the user enacting the request.Zane
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From ReviewSpancake

© 2022 - 2024 — McMap. All rights reserved.