Search code examples
javascriptdjangodjango-tables2

When using Django-tables2, Is there a way to get all the data from the HTML generated table dynamically and client side?


The table class:

class TablaLechos(tables.Table):
    lecho_no = tables.Column(empty_values=())
    distancia = InputColumn(empty_values=())
    varilla_no = InputColumn(empty_values=())
    area_varilla = tables.Column(default="-")
    varillas_en_lecho = InputColumn(empty_values=())

The view that send the table object to the html file:

def index(request):
    """The home page of diseno_columnas"""
    tabla = TablaLechos([{} for n in range(10)]) # Empty dict for 10 rows.
    context = {'tabla': tabla}
    return render(request=request, template_name='diseno_columnas/index.html', context=context)

In the html file:

{% render_table tabla %}
<button type="button" name="button" class="btn btn-primary" onClick="methodThatNeedsTheData()">Graph!</button>

The app is meant to graph a chart on a html canvas element based on the data input of the table. The button will redraw using JS and the actual table values every time it is pressed.


Solution

  • Currently, there is no standard way to do this. A possible solution might be to convert the data you pass to the table to JSON, add that to the context and make it available to your javascript function by outputting it in your template.

    Another option is to use javascript to get the values from the table you just rendered. Since you seem to have input fields, which can be changed by the user and the button has the text 'Graph' this might be the better solution for your use case: the graphing will reflect the current data in the table, in stead of the initial data present in the table when the page was rendered.