Django ModelForm重写密码字段:UpdateView初始值不可见且未保存
解决方案
1. 修复密码输入框不显示初始值的问题
PasswordInput 组件默认不会渲染初始值(render_value=False),若要让它以星号形式显示现有加密密码,只需给组件添加 render_value=True 参数:
class FlowStockAutoForm(forms.ModelForm): class Meta: model = FlowStockAuto exclude = ['fl_st_auto_report_cross_import', ] # 修改PasswordInput,开启初始值渲染 fl_st_auto_pwd = forms.CharField( widget=forms.PasswordInput(render_value=True), label="Password", required=False, help_text="BlaBla" ) def __init__(self, *args, **kwargs): super(FlowStockAutoForm, self).__init__(*args, **kwargs) self.fields['fl_st_auto_pwd'].initial = self.instance.fl_st_auto_pwd
2. 避免更新其他字段时密码被清空
当用户仅修改其他字段、未填写密码框时,表单会提交空字符串覆盖原有密码。在 save 方法中添加判断逻辑:若密码字段为空则保留原有加密值,若有新输入则重新加密保存:
import bcrypt class FlowStockAutoForm(forms.ModelForm): # ... 上述代码保持不变 ... def save(self, commit=True): instance = super().save(commit=False) new_pwd = self.cleaned_data.get('fl_st_auto_pwd') # 仅当输入新密码时才执行加密替换 if new_pwd: hashed_pwd = bcrypt.hashpw(new_pwd.encode('utf-8'), bcrypt.gensalt()).decode('utf-8') instance.fl_st_auto_pwd = hashed_pwd if commit: instance.save() return instance
关键注意事项
- 确保模型中
fl_st_auto_pwd字段的max_length至少设置为 60,因为Bcrypt加密后的字符串固定为60位长度。 - 若希望密码框完全隐藏(而非星号显示),可改用
HiddenInput组件,但需额外添加“修改密码”触发逻辑(比如按钮切换显示密码框)。
内容的提问来源于stack exchange,提问作者Abpostman1
相关产品推荐
相关产品推荐

