0

SOLVED

Explanation here: Performing a getattr() style lookup in a django template

I am looking to build tables on our business website dynamically. At the moment we have multiple pages with tables and filters that allow for search but I have to go in and construct a table for each of them based on the data that should be displayed. I was hoping to find a way to use one main template file that can encompass most instances for creating a new page. The difficulty I am having is trying to loop through the data and place it in the correct cell.

(Some code has been removed for readability.)

View:

def newDynamicView(request):
    jobs = Jobstable.objects.all().order_by('-index')

    filter = NewFilter(data, queryset = jobs)

    fields_model = filter._meta.fields
    fields_text = []

    for field in fields_model:
        fields_text.append(FIELD_NAME_TEXT[field])

    return render(request, 'MYSQLViewer/olivia.html', {'filter': filter, 'fields_model': fields_model, 'fields_display': fields_text})

Current Template (Relevant info):

<div class="table-responsive">
  <table id="data_table" class="table table-dark table-bordered table-responsive">
    <thead class="thead-light">
      {% for field in fields_display %}
        <th>{{field}}</th>
      {% endfor %}
    </thead>
    <tbody>
      {% for job in filter.qs %}
      <tr>
          {% for model_field in fields_model %}
            <td class="pt-3-half edit {{model_field}}" contenteditable="true" id="{{model_field}}-{{job.index}}">{{job.model_field}}</td>
          {% endfor %}
      </tr>
      {% endfor %}
    </tbody>
  </table>

From what I understand, the problem (and possible solution?) lies in this tag:

{{job.model_field}}

My idea was to grab the job attribute using model_field but obviously, that doesn't work.

In its current state, all data is passed from view to template correctly.

Any help is greatly appreciated.

Trevato
  • 1
  • 1
  • 1
  • 1
    From what I can tell it seems like your question is not related to 'building tables dynamically with filters' but is to do with dynamic attribute access on a model instance. You will probably need a custom template tag https://stackoverflow.com/questions/844746/performing-a-getattr-style-lookup-in-a-django-template – ChidG Jan 23 '20 at 06:32
  • @ChidG this looks very promising. All my googling never led me to that thread. Thanks for the help. – Trevato Jan 24 '20 at 00:06
  • Update: That worked like a charm. – Trevato Jan 24 '20 at 00:41

0 Answers0