You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中UpdateView编辑用户资料表单不显示问题求助

问题解决步骤

1. 修复get_context_data方法

你的UserSettings视图中,get_context_data方法没有返回合并后的上下文,导致模板无法获取form变量,这是表单不显示的核心原因。修改代码如下:

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    c_def = self.get_user_context(title='Settings')
    # 合并自定义上下文到默认上下文
    context.update(c_def)
    # 返回最终上下文供模板使用
    return context

2. 修正密码字段的Widget(可选但关键)

UpdateUserForm中密码字段使用TextInput会明文显示密码,且直接修改User模型的password字段不会自动哈希存储,建议调整为:

class UpdateUserForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control form-input form__input'}), required=False)
    confirm_password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control form-input form__input'}), required=False)

    class Meta:
        model = User
        fields = ('username',)

    def clean(self):
        cleaned_data = super().clean()
        password = cleaned_data.get('password')
        confirm_password = cleaned_data.get('confirm_password')
        if password and password != confirm_password:
            self.add_error('confirm_password', '密码不匹配')
        return cleaned_data

    def save(self, commit=True):
        user = super().save(commit=False)
        if self.cleaned_data['password']:
            user.set_password(self.cleaned_data['password'])
        if commit:
            user.save()
        return user

3. 额外检查点

  • 确认用户已正常登录(LoginRequiredMixin会自动重定向未登录用户,能进入settings页面则登录状态无问题)
  • 排查DataMixin的get_user_context方法,确保它没有覆盖或干扰form变量的传递

内容的提问来源于stack exchange,提问作者Hallteon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 18:06:27