0

我试图修改当前用户的数据但没有成功,需要一些帮助。

def account_admin(request):
    if request.method == 'POST':
        mod_form = ModificationForm(request.POST)
        if mod_form.is_valid():
            user = User.objects.get(request.user)
            user.set_password(form.cleaned_data['password1'])
            user.email = form.cleaned_data['email']
            user.save
            return HttpResponseRedirect('/register/success/')
    else:
        mod_form = ModificationForm()

    variables = RequestContext(request, {
        'mod_form': mod_form
    })
    return render_to_response('registration/account.html', variables)
4

4 回答 4

2

request.user已经是用户的一个实例,没有必要再做一个查询。

另外,您实际上需要调用 save().

于 2013-07-31T19:44:38.037 回答
1

你的问题在这里:

user = User.objects.get(request.user)

理想情况下,它本来是

user = User.objects.get(id=request.user.id)

您不需要查询来在此处检索用户对象,因为request.user计算结果为已登录用户对象的实例。

user = request.user
user.set_password(form.cleaned_data['password1'])
user.email = form.cleaned_data['email']
user.save()

应该管用

另外,请确保您拥有该方法的@login_required装饰器account_admin

于 2013-07-31T19:35:49.570 回答
0

您似乎从上述帖子中得到了答案,但我注意到您没有对用户进行身份验证(您可能在我不知道的其他地方做过)。如果您想这样做,请尝试 login_reqired 装饰器https://docs.djangoproject.com/en/1.5/topics/auth/default/#django.contrib.auth.decorators.login_required

于 2013-07-31T20:45:37.423 回答
0

非常感谢 karthikr 和丹尼尔!这是我如何让它工作的:

def account_admin(request):
if request.method == 'POST':
    mod_form = ModificationForm(request.POST)
    if mod_form.is_valid():
        user = User.objects.get(id=request.user.id)
        user.set_password(mod_form.cleaned_data['password1'])
        user.email = mod_form.cleaned_data['email']
        user.save()
        return HttpResponseRedirect('/register/success/')
else:
    mod_form = ModificationForm()

variables = RequestContext(request, {
    'mod_form': mod_form
})
return render_to_response('registration/account.html', variables)

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

karthikr,我还在学习 django,我不明白你对装饰器 @login_required 的建议。它有什么作用?

于 2013-08-01T09:29:37.083 回答