Django: Only update fields that have been changed in UpdateView

自古美人都是妖i 提交于 2019-11-30 23:22:04

i'm using a custom hash during update process to encrypt passwords. When i visit the edit page and hit update button, the old password in its current encrypted form gets re-encrypted hence losing the old password

I would handle that by not including password itself in the form. Instead, I would add a new field (something like new_password) to allow entering a new password. Then, in your is_valid method, set the password to the hashed value of that field if there's content.

You should also use the sensitive value filtering tools to prevent user passwords from showing up in emailed error reports.

class UpdateForm(forms.ModelForm):
    class Meta:
        model = user
        fields = ('first_name', 'last_name', 'email', 'username')
    new_password = forms.CharField(required=False, widget=forms.widgets.PasswordInput)

And then in your view:

@sensitive_variables('new_password')
@sensitive_post_parameters('new_password')
def form_valid(self, form):
    clean = form.cleaned_data
    new_password = clean.get('new_password')
    if new_password:
        #encrypt plain password
        form.instance.password = hash_password(new_password)
    return super(AccountUpdate, self).form_valid(form)

The easiest way would be to pre-populate the fields with what's already there. Do this on the template with {{ account.name }} or whatever.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!