如何基于模型的一个字段来公开模型b的某些特定字段?

2024-09-30 01:19:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个ModelForm,如果设备的device_type等于DC,它将显示ControlInstruction的某些特定字段。否则显示所有字段。在

假设

if device type == 'DC':
   show these filed in form-> on_off_flag, speed_flag, direction_flag
else:
   show all

我怎么能做到呢?在

^{pr2}$

Tags: informifondevicetypeshowdc
2条回答

我建议创建两个表单,一个只包含DC设备的字段,另一个包含所有字段的表单。然后在视图中,根据设备类型选择要使用的窗体。在

class DeviceForm(forms.ModelForm):
     class Meta:
         model = Device
         fields = "__all__"

     def __init__(self,*args,**kwargs):
         super().__init__(*args, **kwargs)
         if self.instance.pk:
              if self.instance.device_type != "DC":
                   del self.fields["on_off_flag"]
                   del self.fields["speed_flag"]
                   del self.fields["direction_flag"]

但我不推荐,因为你会发现这种方法是非常有限的

相关问题 更多 >

    热门问题