Skip to main content
 首页 » 编程设计

python之Django之CustomModelForm 中的 'extra_fields' 在尝试加载该表单时在模型内联接口(interface)中给出 'Unable to lookuup' 错误

2024年08月14日46yjmyzz

我有一个名为 Question 的应用,我在 models.py 中定义了两个模型 Question 和 Alternative 如下:

class Question(models.Model): 
 
    question = models.CharField(max_length=255, blank=False, null=False) 
    chapter = models.ForeignKey(Chapter, on_delete=models.CASCADE) 
    rating = models.IntegerField(default=1) 
 
 
class Alternative(models.Model): 
 
    alternative = models.CharField(max_length=255, blank=False, null=False) 
    question = models.ForeignKey(Question, on_delete=models.CASCADE) 

我制作了一个自定义表单 AlternativeForm,我在其中创建了一个额外的字段,我希望它出现在我的 Alternative forms 以及 Question 管理 View ,替代字段将出现在内联 View 中 但额外的字段值不会保存在数据库中(因为我想对这些字段的值进行一些手动操作)。我的 forms.py 如下:

class AlternativeForm(forms.ModelForm): 
 
    extra_field = forms.BooleanField(required=False) 
 
    def save(self, commit=True): 
        extra_field = self.cleaned_data.get('extra_field', None) 
        # will do something with extra_field here... 
        return super(AlternativeForm, self).save(commit=commit) 
 
    class Meta: 
        model = Alternative 
        fields = '__all__' 

在我的 admin.py 中,我在它们之间建立了如下内联关系:

class AlternativeInline(admin.TabularInline): 
    form = AlternativeForm 
    model = Alternative 
 
@admin.register(Question) 
class QuestionAdmin(admin.ModelAdmin): 
    inlines = [AlternativeInline,] 
 
@admin.register(Alternative) 
class AlternativeAdmin(admin.ModelAdmin): 
    model = Alternative 
    form  = AlternativeForm 

在这种情况下,我得到 AttributeError: Unable to lookup 'extra_field' on Alternative or AlternativeInline。我想在 Question 应用管理 View 的内联 View 中显示那些额外的字段。有什么办法可以做到,或者我目前的做法有什么问题。 谢谢。

请您参考如下方法:

我在推测这个时找到了解决方案 post .应该像下面这样在自定义字段中定义 label 字段以避免这样的错误 AttributeError: Unable to lookup 'extra_field' on Alternative or AlternativeInline。

class AlternativeForm(forms.ModelForm): 
 
    extra_field = forms.BooleanField(label='is_answer', required=False) 
 
    def save(self, commit=True): 
        # extra_field = self.cleaned_data.get('extra_field', None) 
        # ...do something with extra_field here... 
        return super(AlternativeForm, self).save(commit=commit)