Django admin.py 试图保存多个字段时出现ValueError错误

问题描述 投票:0回答:1

我试图在Django中创建一个带有manytomany字段的模型,使用默认的admin.py接口,我得到了一个ValueError:需要有一个字段 "id "的值才能使用这个many-to-many关系。

我知道在填充多对多字段之前需要保存实例,因为它是一个单独的表,但是我没有手动保存,而是依靠admin.py。我的应用程序中有一个单独的模型,它有一个多对多字段,可以在admin.py中正常保存,所以我不确定问题出在哪里。

我的模型代码是

class CaseFeature(models.Model):
"""Case-specific history features"""
    case = models.ForeignKey(
            Case, 
            on_delete=models.CASCADE, 
            related_name="features",
            db_index=True)
    feature_name = models.ForeignKey(
            CoreFeature, 
            on_delete=models.PROTECT,
            db_index=True)
    response = models.TextField("Patient Response", max_length=500)
    clerking_text = models.TextField(max_length=400)
    tooltip = models.CharField(max_length=200, blank=True)
    important = models.BooleanField()
    answered_clarifying_qs = models.ManyToManyField(CoreClarifying, blank=True)

    def clean(self):
        # Make sure answered_clarifying are valid for this symptom
        if self.answered_clarifying_qs not in self.feature_name.clarifying_qs:
            raise ValidationError(_('Answered clarifying Qs do not match this symptom'))


    def __str__(self):
        return f"{self.case} - {self.feature_name}"

我的admin. py是: (没有任何变化,当我把这个注释出来时,我还是得到一个错误的值)

class CaseFeatureAdmin(admin.ModelAdmin):
        formfield_overrides = {
        models.TextField: {'widget': forms.Textarea(attrs={'rows':5})}
    }
...
admin.site.register(CaseFeature, CaseFeatureAdmin)
python django django-admin many-to-many django-orm
1个回答
0
投票

这个错误是由于保存前发生的clean方法造成的。解决方法是将清理验证规则移到ModelForm中,结果成功了。

© www.soinside.com 2019 - 2024. All rights reserved.