' AnonymousUser'对象没有属性' _meta'当试图更新用户时

时间:2018-01-08 13:18:43

标签: django django-views

在我的应用中,我在尝试更新用户信息时遇到错误。

我的代码如下:

def CandidateSignIn(request, uidb64, token):
    try:
        uid = force_text(urlsafe_base64_decode(uidb64))
        user = MyUser.objects.get(pk=uid)
    except(TypeError, ValueError, OverflowError, User.DoesNotExist):
        user = None

    if user is not None and account_activation_token.check_token(user, token):
        user.is_active = True
        user.save()
        login(request, user)

    registered  = False
    if request.method == "POST":
        form = TeamMembersFormUpdate(data=request.POST, instance=request.user)

        if form.is_valid():
            user = form.save()
            user.set_password(user.password)
            user.save()
            #registered = True
            return HttpResponseRedirect(reverse('registration:HRlogin'))

        else:
            print("Error!")
    else:
        form = TeamMembersFormUpdate()
    return render(request,'candidateSignIn.html',
                            {'form':form,
                            'registered':registered})

显然我从行

中得到了错误
form = TeamMembersFormUpdate(data=request.POST, instance=request.user)

你对如何解决这个问题有任何想法吗?

1 个答案:

答案 0 :(得分:1)

您正在使用

行记录用户

11:login(request, user)

但是除非从您所在的视图返回,否则不会更新中间件,因此您将获得相同的匿名用户实例

所以你只需用'用户'替换request.user。你在第4行

它会做正确的事情

...
if request.method == "POST" and user:
    form = TeamMembersFormUpdate(data=request.POST, instance=user)
    #rest here
#if you have no such user 
else: 
    form = TeamMembersFormUpdate()
return render(request,'candidateSignIn.html',
                        {'form':form,
                        'registered':registered})