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.

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)

pythondjango

Answers

answered 2 months ago Manko #1

You will need AJAX connect with django to load the needed elements when something special is selected. Django alone cant do that, as far as I know

probably this guide (in another instance) will help you https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html

comments powered by Disqus