str对象没有属性'*'

时间:2016-05-09 09:37:19

标签: python django

我想更新用户的密码,但我有错误

  

str对象没有属性'*'

if request.method == 'POST':
    form = resetPwdForm(request.POST)
    if form.is_valid():
        email = form.cleaned_data['email']
        passwordNew = form.cleaned_data['passwordNew']
        passwordConfirm = form.cleaned_data['passwordConfirm']
            #actual password is ok
        if passwordConfirm == passwordNew:
            #new password match confirm
            u = request.POST.get('username', '')
            u.set_password(passwordNew)
            u.save()

问题在于u.set_password(passwordNew)

2 个答案:

答案 0 :(得分:6)

u不是您想要的User模型的实例,而是来自POST表单的字符串值。您需要做的是获取User实例,因为您在表单字段中使用了什么用户名

    u = User.objects.get(username=request.POST.get('username', ''))

当没有此类用户使用用户名

时,您还必须处理这种情况
    try:
        u = User.objects.get(username=request.POST.get('username', ''))
        #setting password and whatever...
    except User.DoesNotExist:
        #do something

答案 1 :(得分:0)

您可以按照以下方式获取:

u = request.POST.get('username', '')
NewPassword=set_password(passwordNew)
userobj = User.objects.get(username=u)
query = User.objects.filter(username=userobj).update(password=NewPassword)