Python Django,基于管理中的form.instance更改表单字段
我有一个使用内联线的管理页面。我想根据页面上父模型的状态更改内联表单中的字段。有没有办法在内联表单对象中检查这一点 我有几个相互依赖的模型。为了减少点击次数,我希望能够一次创建它们,但是一旦数据库条目存在,就会引入一些用户友好的功能(例如,Python Django,基于管理中的form.instance更改表单字段,python,django,forms,admin,Python,Django,Forms,Admin,我有一个使用内联线的管理页面。我想根据页面上父模型的状态更改内联表单中的字段。有没有办法在内联表单对象中检查这一点 我有几个相互依赖的模型。为了减少点击次数,我希望能够一次创建它们,但是一旦数据库条目存在,就会引入一些用户友好的功能(例如,ChoiceField,而不是IntegerField,用于设置Element().quality) #proj/elements/models.py ... class Group(models.Model): """A group of eleme
ChoiceField
,而不是IntegerField
,用于设置Element().quality
)
#proj/elements/models.py
...
class Group(models.Model):
"""A group of elements"""
name = models.CharField(max_length=50)
class QualityChoice(models.Model):
"""Translates quality values to human-readable descriptions
within a group"""
value = models.SmallIntegerField()
name = models.CharField(max_length=50)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
class Meta:
unique_together = ('value', 'group')
class Element(models.Model):
"""An element"""
name = models.CharField(max_length=50)
quality = models.SmallIntegerField()
group = models.ForeignKey(Group, on_delete=models.CASCADE)
以下是我想做的:
#proj/elements/admin.py
...
class ElementForm(ModelForm):
class Meta:
model = Element
fields = ('name', 'description', 'quality', 'group', 'marker_id')
def __init__(self, *args, **kwargs):
super(ElementForm, self).__init__(*args, **kwargs)
if self.instance.group:
# Set quality field to be a select scoped to valid choices
# for the group. Assume `choices` is set elsewhere
self.fields['quality'] = ChoiceField(choices=choices)
class ElementInline(TabularInline):
model = Element
form = ElementForm
extra = 0
exclude = ('marker_id',)
class QualityInline(TabularInline):
model = QualityChoice
extra = 0
class GroupAdmin(ModelAdmin):
list_display = ('name',)
list_display_links = ('name',)
inlines = [QualityChoiceInline, ElementInline,]
...
在添加组页面上,质量
字段应为整型字段
,因为没有为组设置质量选择
值。用户只需手动映射值即可
在更改组页面上,质量
字段应该是一个选项字段
,其中填充了适用于当前组的选项
但是,在实例化表单时,实例没有设置组
,因此ElementForm().fields['quality']
默认为整型字段
有什么办法可以解决这个问题吗