How can I hide field based on a dropdown value in a Django Form

43 Views Asked by At

I am developing an plugin for Netbox, which is a Django App that uses templates. My problem ist that one of the values is a crop down which tells me the type of the device this form is about.

The code I have is using some button to toggle the tabs, but I would rather have the value of "deployment_type" in the form to toggle the tabs.

<div class="field-group my-5">
      <div class="row mb-2">
        <h5 class="offset-sm-3">{% trans "Device Details" %}</h5>
      </div>
      {% render_field form.deployment_type %}
 
    </div>
    <div class="field-group my-5">
      <div class="row mb-2">
        <div class="offset-sm-3">
          <ul class="nav nav-pills" role="tablist">
            <li role="presentation" class="nav-item">
              <button role="tab" type="button" id="device_tab" data-bs-toggle="tab" aria-controls="device" data-bs-target="#device" class="nav-link {% if not form.initial.vdc and not form.initial.vm %}active{% endif %}">
                {% trans "Physcial Device" %}
              </button>
            </li>
            <li role="presentation" class="nav-item">
              <button role="tab" type="button" id="vdc_tab" data-bs-toggle="tab" aria-controls="vdc" data-bs-target="#vdc" class="nav-link {% if form.initial.vdc %}active{% endif %}">
                {% trans "Virtual Device Context" %}
              </button>
            </li>
            <li role="presentation" class="nav-item">
              <button role="tab" type="button" id="vm_tab" data-bs-toggle="tab" aria-controls="vm" data-bs-target="#vm" class="nav-link {% if form.initial.vm %}active{% endif %}">
                {% trans "Virtual Machine" %}
              </button>
            </li>
          </ul>
        </div>
      </div>
      <div class="tab-content p-0 border-0">
        <div class="tab-pane {% if not form.initial.vdc and not form.initial.vm %}active{% endif %}" id="device" role="tabpanel" aria-labeled-by="device_tab">
          {% render_field form.device_type %}
        </div>
        <div class="tab-pane {% if form.initial.vdc %}active{% endif %}" id="vdc" role="tabpanel" aria-labeled-by="vdc_tab">
          {% render_field form.primary_device %}
        </div>
        <div class="tab-pane {% if form.initial.vm %}active{% endif %}" id="vm" role="tabpanel" aria-labeled-by="vm_tab">
          {% render_field form.primary_cluster %}
        </div>
      </div>
    </div>

I have tried to get rid of the button too and make the tab activ depending on the value of "deployment_type", but that did not work. I can change the dropdown but all tabs are not visible.

<div class="tab-pane {% if form.deployment_type == 'Physical-Device' %}active{% endif %}" id="vm" role="tabpanel" aria-labeled-by="vm_tab">
0

There are 0 best solutions below