我有一个应用程序Question,我在其中定义了两个模型Question并Alternative在 models.py 中命名如下:
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)
Run Code Online (Sandbox Code Playgroud)
我制作了一个自定义表单AlternativeForm,我在其中创建了一个额外的字段,我想将其显示在我的Alternative forms以及Question管理视图中,其中替代字段将出现在内联视图中但额外的字段值不会保存在数据库中(因为我想要使用该字段的值进行一些手动操作)。我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__'
Run Code Online (Sandbox Code Playgroud)
在我中,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
Run Code Online (Sandbox Code Playgroud)
我正在处理AttributeError: Unable to lookup 'extra_field' on Alternative or AlternativeInline这种情况。我想在应用程序管理视图的内联视图中显示这些额外的字段。有什么办法可以做到,或者我目前的方法有什么问题。谢谢。Question
我在推测这篇文章时找到了解决方案。应该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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
800 次 |
| 最近记录: |