How to expose some specific fields of model

I want to create a ModelForm which gonna show some specific field of ControlInstruction if device_type of Device is equals DC . Otherwise show all fields.

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

How can I do that?


    class Device(models.Model):
        DEVICE_TYPES = (
            ('AC', 'AC MOTOR'),
            ('DC', 'DC MOTOR'),
        )
        user = models.ForeignKey(User, on_delete=models.CASCADE)
        device_id = models.CharField(max_length=64, unique=True, blank=False)
        device_name = models.CharField(max_length=100, blank=False)
        device_model = models.CharField(max_length=10)
        device_type = models.CharField(max_length=2, choices=DEVICE_TYPES, blank=False)
        location = models.CharField(max_length=150)

        def __str__(self):
            return self.device_name

    class ControlInstruction(models.Model):
        DIRECTION_CHOICES = (
            ('FW', 'Forward'),
            ('BW', 'Backward'),
        )
        # OneToOneField is is similar to a ForeignKey with unique=True, but the “reverse”
        # side of the relation will directly return a single object.
        device = models.OneToOneField(Device, on_delete=models.CASCADE, primary_key=True)
        on_off_flag = models.BooleanField(default=False)
        voltage_flag = models.FloatField(max_length=20, default=0)
        current_flag = models.FloatField(max_length=20, default=0)
        speed_flag = models.IntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(100)])
        direction_flag = models.CharField(max_length=2, choices=DIRECTION_CHOICES, default='FW')
        frequency_flag = models.IntegerField(default=0)


You may try to override form init method, like it:

class ControlInstructionForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(ControlInstructionForm, self).__init__(*args, **kwargs)
        if self.instance and self.instance.device and self.instance.device.device_type == 'DC':
            # remove fileds for example 
            self.fields.pop('current_flag')

hope it help

链接地址: http://www.djcxy.com/p/38684.html

上一篇: 使用标签模型创建ManytoMany关系

下一篇: 如何揭示模型的某些特定领域