Django,在admin中基于form.instance更改表单字段

时间:2016-12-01 19:30:51

标签: python django forms admin

我有一个使用内联的管理页面。我想根据页面上父模型的状态更改内联表单中的字段。有没有办法在内联表单对象中检查这个?

我有一些相互依赖的模型。为了减少点击次数,我希望能够一次创建所有这些内容,但是一旦存在数据库条目,就会引入一些用户友好的功能(即ChoiceField而不是IntegerField来设置{ {1}}。

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,] ... 字段应为quality,因为没有为该组设置IntegerField值。用户只需手动映射值。

更改组页面上,QualityChoice字段应为quality,其中填充了作为当前组范围的选项。

但是,实例在实例化表单时没有设置ChoiceField,因此group默认为ElementForm().fields['quality']

有什么方法可以解决这个问题吗?

0 个答案:

没有答案