简体   繁体   English

Django模板渲染在无效的编辑配置文件表单上更改了用户名

[英]Django template rendering changed username on invalid edit profile form

I have a view where it is possible to change user's name and username. 我认为可以更改用户名和用户名。 Field name has custom validators. 字段名称具有自定义验证器。 If validators fail, form is not saved. 如果验证程序失败,则不会保存表格。 It even works. 它甚至可以工作。

The only problem is that I render username in my base.html template with this code 唯一的问题是,我使用此代码在base.html模板中呈现了用户名

Login as {{ user.username }}

and username is rendered changed even when form is failing and user's username in the database is not changed. 并且即使表单失败并且数据库中用户的用户名没有更改,用户名也会更改。

When I go to another URL, username is correct (it is unchanged value). 当我转到另一个URL时,用户名正确(值不变)。

Can you help me with that? 你能帮我吗? It feels like bug and not a mistake in my code. 感觉像是错误,而不是我的代码中的错误。

Code of my edit_profile view. 我的edit_profile视图的代码。

def edit_profile(request):

    if request.method == 'POST':
        form = EditProfileForm(request.POST, instance=request.user)

        if form.is_valid():
            form.save()
            return redirect('profile')
        else:
            return render(request, 'accounts/edit_profile.html', {'form': form})

    form = EditProfileForm(instance=request.user)
    return render(request, 'accounts/edit_profile.html', {'form': form} )

I would say this functionality is by design in Django. 我会说这个功能是在Django中设计的。 The form is modifying the request.user object directly, it will be modified by the POST data before being rendered. 表单是直接修改request.user对象,它将在呈现之前由POST数据进行修改。

An alternate solution would be to retrieve a separate copy of the user object, and not modify the request.user object directly. 一种替代解决方案是检索用户对象的单独副本,而不直接修改request.user对象。 Then the "live" user object is only modified after the object has been validated and stored to the DB (ie after the next request). 然后,仅在验证对象并将其存储到DB之后(即下一个请求之后),才修改“活动”用户对象。

It would probably also be safer, as it could potentially have side effects in other parts of the rendering. 这可能也更安全,因为它可能在渲染的其他部分产生副作用。 For example, if somewhere in your code you checked the user name against a role table, the user could potentially (temporarily, for the scope of the rendering) elevate his/her privileges by renaming himself to "admin". 例如,如果您在代码中的某个位置根据角色表检查了用户名,则该用户可以通过将自己重命名为“ admin”来潜在地(临时,在渲染范围内)提升他/她的特权。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM