Django UpdateView编辑投诉表单时user字段自动变为Null问题求助
问题解决方案
问题根源
EditComplaint视图的form_valid方法字段名赋值错误:你给实例赋值的是author字段,但Complaint模型中关联用户的实际字段名为user,字段不匹配导致用户关联关系没有被正确保存ComplaintForm设置了fields = '__all__',会将user字段纳入表单提交项,如果你编辑页面没有渲染user字段,提交时该字段会被空值覆盖,导致原有用户关联丢失
修复步骤
- 修正视图
form_valid方法的字段名
把原有赋值语句的字段从author改为user,确保用户关联关系被正确写入:
def form_valid(self, form): if form.is_valid(): # 替换原有author字段为模型实际的user字段 form.instance.user = self.request.user return super().form_valid(form)
- 从表单中排除
user字段
修改ComplaintForm的Meta配置,不要将不需要用户手动填写的user字段纳入表单范围,两种修改方式二选一即可:
class ComplaintForm(ModelForm): class Meta: model = Complaint # 方式1:显式列出所有需要用户填写的字段,排除user fields = ['reportnumber', 'eventdate', 'event_type', 'device_problem', 'manufacturer', 'product_code', 'brand_name', 'exemption', 'patient_problem', 'event_text', 'document'] # 方式2:直接排除user字段,无需改动原有字段列表 # exclude = ['user'] widgets = { # 原有widget配置保持不变即可 'reportnumber': forms.TextInput(attrs={'placeholder': 'Report number'}), 'event_type': forms.TextInput(attrs={'placeholder': 'Event type'}), 'eventdate': DateInput(), 'device_problem': forms.TextInput(attrs={'placeholder': 'Device Problem'}), 'event_text': forms.Textarea(attrs={'style': 'height: 130px;width:760px'}), 'manufacturer': forms.TextInput(attrs={'placeholder': 'Enter Manufacturer Name'}), 'product_code': forms.TextInput(attrs={'placeholder': 'Enter Product Code'}), 'brand_name': forms.TextInput(attrs={'placeholder': 'Enter Brand Name'}), 'exemption': forms.TextInput(attrs={'placeholder': 'Enter Exemption'}), 'patient_problem': forms.TextInput(attrs={'placeholder': 'Enter Patient Problem'}), }
- (可选优化)如果你的业务逻辑中投诉记录必须关联用户,可以把模型中
user字段的null=True, blank=True配置删除,从数据库层面避免空值产生:
user = models.ForeignKey(User, on_delete= models.CASCADE)
修改完成后重新测试编辑功能,user字段就不会再被清空,编辑后的记录也能在my-history页面正常展示。
内容的提问来源于stack exchange,提问作者Isha Jagadi
相关产品推荐
相关产品推荐

