Home > Back-end >  Display data from a Django model as a Tree view
Display data from a Django model as a Tree view

Time:09-09

I have a Django model as shown below

    class operationTemplates(models. Model):
    templateID = models.IntegerField(primary_key = True)
    templateCategory = models.CharField(max_length=255, blank=True, null=True)
    templateName = models.CharField(max_length=400, blank=True, null=True)
    templatePreopBundle = models.CharField(max_length=255, blank=True, null=True)
    templatePosition = models.CharField(max_length=20, blank=True, null=True)

I want to display the data as a tree view using either CSS or Javascript. Tree view should order the data by "templateCategory" as follows

- Category1
|__Name1
|__Name2
|__Name3   
  Category2
- Category3
|__Name6
|__Name7
|__Name9
|__Name10

I am using Django2 and Python3.7 Thanks in advance.

CodePudding user response:

Bootstrap 4/5 Seems to come with a tree view, so I'd say that might be the easiest way of doing this..

View

def do(request):
    packed = {}
    for cat in operationTemplates.objects.all().values_list('templateCategory', flat=True).distinct():
        packed['cat'] = operationTemplates.objects.filter(templateCategory=cat)

    data = {
        'packed': packed
    }
    return render(request, 'thing.html', data)

Template

<script>
    // Treeview Initialization
    $(document).ready(function() {
      $('.treeview-animated').mdbTreeview();
    });
</script>

<div >
  <h6 >Things</h6>
  <hr>
  <ul >
    {% for cat, list in packed %}
        <li >
          <a >
            <i ></i>
            <span>{{cat}}</span>
          </a>
          <ul >
            {% for i in list %}
                <li>
                  <div >{{i.name}}
                </li>
            {% endfor %}
          </ul>
        </li>
    {% endfor %}
  </ul>
</div>
  • Related