Jabda
Jabda

Reputation: 1792

Django Interactive lists based on Database query and user selection

I would like to create 2 lists in Django.

The first one lists all results returned from a db query (external query). The second pane is blank until a selection is done. This is single selection drop down

Once the user selects an item in the first drop down a list of all results for that selection is displayed (based on another db query). This selection is multi select. I am not sure what elements allow multi select in Django

Example. Select City in first list, get a list of all centres in second list, select multiple centres in second list and submit

The information being queried is from an external db, I could also use API, but my difficulty is not in the query but how to create the elements and update them based on selection. I am also using django-bootstrap3

Upvotes: 0

Views: 223

Answers (1)

Mithun Mistry
Mithun Mistry

Reputation: 148

You can use Ajax to query through the database.

$.ajax({
      type: "POST",
      url: "/load_pane/" + $id, //specify your URL which you will create in Django with some ID selected by user from dropdown
      // Specify your CSRF token here, if you do a GET request then it's not needed
      data: $("#form").serialize() // You can send additional data if you want,
      success: function (data) {
          $("#second-pane").html . . . . // Populate second pane with JSON data. (HTML container with multi-select)

          }
         });

And in Django, you can use RESTful API, or for a simple approach Register '/loadpane' (Your URL in routes and make it call this function in views.py)

def populate_pane(request, id):
       if request.POST:
            data = Model.objects(...) #Get whatever data you want using model
            return HttpResponse(json.dumps(data)) #This JSON will be processed by Ajax on front-end in the Multi-Select HTML component.

Follow this link - https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_select_multiple for multi-select HTML component that you can populate by that JSON data you will get from Django on front-end with jQuery in success function of Ajax.

Upvotes: 1

Related Questions