我试图让用户删除自己的帐户,但我面临的错误:
AttributeError at/account/delete/testuser1: 'str'对象没有属性'field'
用户也没有被删除。知道为什么吗?我试图使它这样的删除按钮是在帐户页面,当我按下删除,用户被删除并重定向回主页如果你能分享我如何创建一个函数来停用一个帐户,那就太好了……它只是设置is_active = False吗?
html
<form action="{% url 'account:delete_account' username=request.user.username %}" method="GET">{% csrf_token %}
<a class="btn btn-danger btn-sm deleteaccount ml-3" href="{% url 'account:delete_account' username=request.user.username %}">Delete Account</a>
</form>
views.py
def delete_user(request, username):
context = {}
if request.method == 'DELETE':
try:
user = Account.objects.get(username=username)
user.delete()
context['msg'] = 'Bye Bye'
except Exception as e:
context['msg'] = 'Something went wrong!'
else:
context['msg'] = 'Request method should be "DELETE"!'
return redirect(request, 'HomeFeed/snippets/home.html', context)
urls . py
path('delete/<username>', delete_user, name='delete_account'),
models.py
class Account(AbstractBaseUser):
email = models.EmailField(verbose_name="email", max_length=60, unique=True)
username = models.CharField(max_length=30, unique=True)
我解决了这个问题,只需改变视图:它起作用了,但它似乎太容易是真实的。有人能检查一下它是否有效吗?我需要请求之类的东西吗?方法= =删除等等?
def delete_user(request, username):
context = {}
user = Account.objects.get(username=username)
logout(request)
user.delete()
return redirect('HomeFeed:main')