[Flask] Datatables question

Craig Amundsen amundsen.craig at gene.com
Tue Aug 1 11:13:45 EDT 2017

Hi -

I've googled around a bit and am having trouble figuring out how to pass a
value from a flask page back to the view method that produces the json for
loading a datatables table.

Currently I'm using datatables to display all the entries in a given table
with great success:

in an html template where I have table with id="test_table":
        $(document).ready(function() { $('#test_table').DataTable( { "ajax"
: $SCRIPT_ROOT + "/_get-test-rows" } ); } );

in views.py:

def get_test_rows():
    trows = Test.query.order_by(Test.name)
    rows = [ [tr.name, tr.x.name, tr.y, tr.z] for tr in trows]
    return josnify(data = rows)

In my above example, I have another table X that tr.x points to. I'd like
to have a page that displays information about individual rows in X that
has a table showing all rows from Test that have that point to that
particular row in X.

def show_x(id):
    x = X.query.get_or_404(id)
    return render_template('x.html', x = x)

I know I can just get all the Test rows I need with tr =
Test.query.filter_by(x_id = id).order_by(Test.name) pass them to
render_template and render the table myself, but I'd prefer to have a
jQuery call in the page that gets the rows of Test where x_id = x.id.
Sometimes there are many rows of Test that will be shown and I'd like the
page to start loading so the User sees that the click did get through and
now we're waiting for the values to get loaded.

My problem is that I can't figure out how to write the <script> call to
include x.id and how to read that value in my view function. I tried this:

$(document).ready(function() { $('#test_table').DataTable( { "ajax" : {
"url" : $SCRIPT_ROOT + "/_get-x-test-rows", "data" : { "id" : {{ x.id }} }}
); } );


def get_x_test_rows(id):
    tr = Test.query.filter_by(x_id = id).order_by(Test.name)

But the view method never gets called. I think I probably need to do
something along the lines of

def get_x_test_rows()
    id = extract the id value from something somehow
    tr = Test.query.filter_by(x_id = id).order_by(Test.name)

But I haven't been able to figure out how to do that.

Could someone point me in the right direction to figure out how to do this?

- Craig
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/flask/attachments/20170801/830d4ed6/attachment.html>

More information about the Flask mailing list