'Django Dependent/Chained Dropdown List in a filter
I am using Django to implement my web page; in this page I have a classic item list that I manage with a for loop. I also implement a filter as a form (with search button) to filter the items.
I know how can I implement a dropdown List (first code) and I know how can I implement a form filter (second code).
DROPDOWN LIST (JQUERY CODE)
    <script>
        $( document ).ready(function()
        {
            var $provvar = $("#provddl");
                $uffvar = $("#uffddl");
                $options = $uffvar.find('option');
                $provvar.on('change',function()
                {
                    $uffvar.html($options.filter('[value="'+this.value+'"]'));
                }).trigger('change');           
        });
    </script>
FORM FILTER
    <form>
        <div>
            <label>C: </label>
                {{ myFilter.form.C }}
        </div>
        <div>
            <label>D: </label>
                {{ myFilter.form.D }}
        </div>
        <button type="submit">Search</button>
    </form>
My problema is that I don't know how can I implement a the Dependent Dropdown List in my filter.
Solution 1:[1]
I can't comment So I am saying what I know. did you want to chain D with C, for that you can use foreign key for D, and load the data of D with ajax using C's id. example:
models.py:
class C(models.Model):
   id = models.PositiveIntegerField(primary_key=True)
   name = models.CharField(max_length=50)
   def __str__(self):
      return self.name
class D(models.Model):
    c= models.ForeignKey(C, on_delete=models.CASCADE)
    name = models.CharField(max_length=50)
    def __str__(self):
        return self.name
Ajax
$.ajax({                       
    url: 'url for loading the data',                    
    data: {
      'c': c's Id       
    },
    success: function (data) {   
      $("#D").html(data);  
    }
  });
html:
<option value="">---------</option>
{% for d in D %}
<option value="{{ d.pk }}">{{ d.name }}</option>
{% endfor %}
views.py:
def load_d(request):
   c_id = request.GET.get('c')
   D = State.objects.filter(c_id=c_id).order_by('name')
   return render(request, 'd_list.html', {'D': D})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source | 
|---|---|
| Solution 1 | Ajay | 
