gpt4 book ai didi

python - ModelForm 的额外字段没有标签,不会在 InlineModelAdmin 中呈现

转载 作者:行者123 更新时间:2023-12-01 07:52:08 24 4
gpt4 key购买 nike

要在管理add页面中添加额外字段,可以使用以下代码:

模型.py:

class Parent(models.Model):
pass


class Child(models.Model):
parent = models.ForeignKey(Parent, on_delete=models.PROTECT)

表单.py:

class ChildForm(forms.ModelForm):
extra_field = forms.CharField()

class Meta:
model = Child
fields = '__all__'

admin.py:

@admin.register(models.Child)
class ChildAdmin(admin.ModelAdmin):
form = forms.ChildForm
<小时/>

Child 内联到 Parent 中的 Parent 时,如何添加相同的额外字段添加页面?

<小时/>

以下 admin.py:

class ChildInline(admin.TabularInline):
model = models.Child
form = forms.ChildForm


@admin.register(models.Parent)
class ParentAdmin(admin.ModelAdmin):
inlines = (ChildInline,)

结果:

Traceback (most recent call last):
File "django/db/models/options.py", line 617, in get_field
return self.fields_map[field_name]
KeyError: 'extra_field'

...

django.core.exceptions.FieldDoesNotExist: Child has no field named 'extra_field'

...

AttributeError: Unable to lookup 'extra_field' on Child or ChildInline

最佳答案

根据this answer添加标签将使内联按预期工作:

class ChildForm(forms.ModelForm):
extra_field = forms.CharField(label='Extra Field')

class Meta:
model = Child
fields = '__all__'

相关票证:https://code.djangoproject.com/ticket/30520#ticket

关于python - ModelForm 的额外字段没有标签,不会在 InlineModelAdmin 中呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56156039/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com