How to use it on python flask
How to use it on python flask
mmcd_96
Posts: 2Questions: 1Answers: 0
Hello i'm trying to integrate DataTables on Flask but i'm facing some difficulties. It's an easiest way to do it ?
This discussion has been closed.
Answers
What are the difficulties?
Are you getting errors?
Kevin
No it's just that i have no tutorial on it. So i have start something but, i'm know that it could not work.
@admin.route('/experts', request_method="GET", renderer="json")
@admin_required
@login_required
def experts():
type = Type.query.filter_by(name='Expert').first()
page = request.args.get('page', 1, type=int)
query = User.query.filter_by(type=type).order_by(User.created_on.desc())
pagination = query.filter_by(type=type).order_by(User.created_on.desc()).paginate(
page, per_page=20, error_out=False)
experts = pagination.items
return render_template('admin/experts.html', experts=experts, pagination=pagination)
This is the code i'm trying to insert DataTables on. Did i insert it here or directly on the template ??
I'm not familiar with Flask, I use CherryPy. Looks like the
experts
function is performing a SQL query (using SQLAlchemy?) and returning HTML. I'm guessing that theadmin/experts.html
is a template that has the Datatables config and that you are trying to pass the results of the SQL query into the page using the variablespagination
andexperts
. Having a look at your experts.html page might be helpful to see how you are using these variables.Also looks like you are trying to implement serverside processing. Do you need serverside processing? Serverside processing is more complicated than client side and is not need unless you have many thousands of rows which delay table display.
For a more standard Datatables approach I would recommend separating the HTML display and SQL processing into two Flask functions. The first returns a standard HTML web page containing the table and Datatables definitions (experts.html). Configure Datatables to perform an Ajax request to a second URL which is another Flask function that processes the SQL query and returns the result as JSON data. This approach will separate the Datatables code from the Python code making it easier to troubleshoot.
Take a look at the
flask.py
code on this page:https://gist.github.com/kaiserama/5732513
It has a function called
get_server_data
which gets the server data then returns it as JSON formatted data. Your code that performs the actual SQL queries can still use the SQLAlchemy approach instead of the example DataTablesServer class on this page.I would also recommend using client side processing if you can. But if your dataset is too large then start with a small data set to test with then once working learn how to use server side processing.
Kevin