How to delete user in django?

一曲冷凌霜 提交于 2019-12-08 03:33:00

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/33715879/how-to-delete-user-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!