How to expose some specific fields of model_b based on a field of model_a?

Abdul Halim Source

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.

if device type == 'DC':
   show these filed in form-> on_off_flag, speed_flag, direction_flag
   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):
            ('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)



answered 8 months ago Bear Brown #1

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 

hope it help

comments powered by Disqus