Home > Software engineering >  Django update content of HTML element on same page based on selected item
Django update content of HTML element on same page based on selected item

Time:05-24

The title is a bit vague as I couldn't think of a way to summarise this.

I have 3 django models. Let's call them root, branch leaf to make it easy. A root can have multiple branches and each branch can have multiple leaves.

In my template I am displaying buttons that are populated from the root objects. When a user clicks one of these buttons I would like to update the content of another element on the same page with all the branches that are children of that root. When a branch is clicked, i'd like to update another element with all the leaves. I'm assuming the process would be the same for the two updates.

I am pretty new to Django but not to programming and I can't seem to find a good explanation of how to detect which 'root' has been clicked and pass that back to django in order to populate the branch elements.

Can anyone offer some guidance? I probably don't need code, just more of an idea of what the workflow is. E.G use onclick to send the name of the clicked item to a javascript function, call out to a python function that gets all the branches, do some magic.......

Thanks Mick

CodePudding user response:

This is more of a JS thing than Django. There are two options, as far as I know, for the kind of dynamic content you want:

  • You can load the whole "tree" (all roots, branches and leaves) with the display style as none and then make change the appropiate ones to another value (block or inline) via javascript when a button is pressed. The onClick function would look something like this for a branch.
function displayBranch(branchId){
  for(let branch of document.getElementsByClass("branch-class"){
    branch.style.display = "none"
    if(branch.id == branchId) branch.style.display = "block"

  }
}
  • Or you can load none, but add endpoints to your Django API to send branches and leaves, then use AJAX calls to retrieve them on a button press. This one requires more code, so I won't include code, but assume that you know basic AJAX and how to create new endpoints in your app.
  • Related