Search code examples
pythondjangoposthandsontable

Getting table from Django POST request and displaying it in handsontable (read value in javascript)


I have to render excel-like table with easy possibility to modify. I have web application in Django with mysql database. When I was searching for a solution I found Handsontable which looks as a good answer to my problem. But now i have a question:

How I can autofill handsontable after submitting a form? I have a form, where user can choose few options and generate tables with data. I have data in table of tables and I'm sending it using POST request.

if request.method == 'POST':
    form = TestForm(request.POST)

    if form.is_valid():
        ### ACCESSING DATA FROM DATABASE
        ### CREATING 2D TABLE

        return render_to_response('rendered.html', {'form' : form, 'my_data' : my_data} ) 

After that I want to display my handsontable and render it with my data. It has to me did by Ajax? With dynamically builded handsontable or what?

I was trying do something with first example from here http://docs.handsontable.com/0.20.2/tutorial-data-sources.html

and overwrite data1 but if my_data is variable sent by my form...

data1 = request.POST["my_data"];

I can't access data from POST like this (JS it's client not server side, yea?)

data1 = {{ my_data }};

this way would be possible inside Django template, not inside <script> </script> block

There is another way except putting "Load data" button with Ajax request for data in POST['my_data'] ? I am just starting with Django and I don't have idea what should I do? :/


Solution

  • If I got your question right, the easiest (but not the most flexible and secure) solution would be to render the js variables just in the Django template:

    Assuming your context var my_data contains the data needed for the Handsontable, put this in your_template.html:

    <script type="text/javascript">
        var myData = "{{ my_data }}";
        // now your data is on the JS side.
    </script>