You need to enable JavaScript to run this app. Django提交用户更新表单报错'str'对象无'_meta'属性如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

Django提交用户更新表单报错'str'对象无'_meta'属性如何解决?

问题触发原因

  • 核心错误来自views.py的post方法:你给ModelForm的instance参数传入了self.request.user.username,这是字符串类型的用户名,而ModelForm要求instance参数必须传入对应模型的实例对象,表单内部会调用实例的_meta属性获取模型元数据,字符串没有该属性,因此触发AttributeError。
  • 额外逻辑问题:你当前使用UserCreationForm作为更新用户信息的表单基类不符合场景,UserCreationForm是专门用于创建新用户的表单,默认强制要求输入两次密码,用户修改个人信息时不需要每次填写密码,会导致正常提交无法通过校验。

修复方案

1. 修正views.py参数与逻辑

修改post方法的instance参数传入request.user(本身就是已登录的CustomUser实例),同时简化get方法的冗余数据库查询,补充校验失败的返回逻辑:

class AllUserUpdate(LoginRequiredMixin, View):
    def get(self, request, *args, **kwargs):
        # 直接用request.user,无需额外查询数据库
        form = CustomUserForm(instance=request.user)
        context = {'form':form}
        return render(request, 'account/AllUserAccount.html', context)

    def post(self, request, *args, **kwargs):
        # instance传request.user实例,不要传username字符串
        form = CustomUserForm(request.POST, request.FILES, instance=request.user)
        if form.is_valid():
            form.save()
            messages.info(request, "信息修改成功!")
            return redirect('all_user_update')
        # 校验失败时把带错误提示的表单传回模板
        context = {'form': form}
        return render(request, 'account/AllUserAccount.html', context)

2. 调整forms.py适配用户更新场景

将表单基类从UserCreationForm替换为ModelForm,支持用户可选修改密码,不填密码则保留原有密码:

from django import forms
from .models import CustomUser

class CustomUserForm(forms.ModelForm):
    # 密码设为非必填,用户不想修改可以留空
    password1 = forms.CharField(
        required=False,
        widget=forms.PasswordInput(attrs={'class': 'form-control mt-2', 'placeholder': '不修改密码请留空...'}),
        label="新密码"
    )
    password2 = forms.CharField(
        required=False,
        widget=forms.PasswordInput(attrs={'class': 'form-control mt-2', 'placeholder': '不修改密码请留空...'}),
        label="确认新密码"
    )

    class Meta:
        model = CustomUser
        fields = ('full_name', 'email', 'user_type', 'phone', 'username')
        widgets = {
            'full_name': forms.TextInput(attrs={'class': 'form-control mt-2'}),
            'username': forms.TextInput(attrs={'class': 'form-control mt-2'}),
            'email': forms.EmailInput(attrs={'class': 'form-control mt-2'}),
            'phone': forms.TextInput(attrs={'class': 'form-control mt-2'}),
            'user_type': forms.Select(attrs={'class': 'form-control mt-2'}),
        }
    
    # 校验两次密码输入是否一致
    def clean(self):
        cleaned_data = super().clean()
        password1 = cleaned_data.get('password1')
        password2 = cleaned_data.get('password2')
        if password1 and password1 != password2:
            raise forms.ValidationError("两次输入的密码不一致")
        return cleaned_data
    
    # 保存时处理密码逻辑
    def save(self, commit=True):
        user = super().save(commit=False)
        password = self.cleaned_data.get('password1')
        if password:
            user.set_password(password)
        if commit:
            user.save()
        return user

如果不需要提供修改密码功能,直接删除表单中password1、password2相关的代码即可,无需额外逻辑。

模板无需修改

原有模板代码已经适配multipart/form-data编码,支持上传文件类字段,可以直接使用。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 15:24:01