Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete user in django?

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?

like image 257
Jand Avatar asked Nov 15 '15 02:11

Jand


People also ask

How do you delete a user in Python?

Deleting a user from your system or server via a python script is a very easy task. You just need to pass the username of the user and the script will remove the details and all the files of that user. This python script uses userdel Linux command to delete the user.

How do I delete a Django record?

To delete a record we do not need a new template, but we need to make some changes to the members template. Of course, you can chose how you want to add a delete button, but in this example, we will add a "delete" link for each record in a new table column. The "delete" link will also contain the ID of each record.

How do I delete a Django project?

To delete the project you can delete the project folder. But this method is good only if you use SQLite as a database. If you use any other database like Postgresql with Django, you need to delete the database manually. This should delete the folder and it's contents.


1 Answers

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

like image 118
doniyor Avatar answered Oct 09 '22 11:10

doniyor