Flask/datatables.js – add buttons to table?


I want to add buttons to a table, like the "Edit" and "Delete" buttons in the image below.

enter image description here

I currently have this:

enter image description here


def index():
    return render_template('server_table.html', title='Recipes')

def data():
    query = Recipe.query

    # search filter
    search = request.args.get('search[value]')
    if search:
        query = query.filter(db.or_(
    total_filtered = query.count()

    # sorting
    order = []
    i = 0
    while True:
        col_index = request.args.get(f'order[{i}][column]')
        if col_index is None:
        col_name = request.args.get(f'columns[{col_index}][data]')
        if col_name not in ['name', 'ingredients_str', 'cook_time']:
            col_name = 'name'
        descending = request.args.get(f'order[{i}][dir]') == 'desc'
        col = getattr(Recipe, col_name)
        if descending:
            col = col.desc()
        i += 1
    if order:
        query = query.order_by(*order)

    # pagination
    start = request.args.get('start', type=int)
    length = request.args.get('length', type=int)
    query = query.offset(start).limit(length)

    # response
    return {
        'data': [recipe.to_dict() for recipe in query],
        'recordsFiltered': total_filtered,
        'recordsTotal': Recipe.query.count(),
        'draw': request.args.get('draw', type=int),

and server_table.html:

{% extends "base.html" %}

{% block content %}
  <table id="data" class="table table-striped">
        <th>Recipe Name</th>
        <th>Cook Time (Mins)</th>
        <th> </th>
{% endblock %}

{% block scripts %}
    $(document).ready(function () {
        ajax: '/api/data',
        serverSide: true,
        columns: [
          {data: 'name'},
          {data: 'ingredients_str', orderable: false},
          {data: 'cook_time', orderable: false}
{% endblock %}

I’m a total newbie to Flask etc, so I just don’t even know where to start. There are a couple similar questions on this site but I couldn’t find any for Flask in particular. Most of my code is copied from this tutorial.


One possibility is to do this:

    $(document).ready(function () {
        ajax: '/api/data',
        serverSide: true,
        columns: [
          {data: 'name'},
          {data: 'ingredients_str', orderable: false},
          {data: 'cook_time', orderable: false},
           "orderable": false,
           "data": null,
           "defaultContent": '<a class="btn btn-primary edit"> Edit </a>'+
                             '<a class="btn btn-danger delete"> Delete </a>'

Answered By – Tobin

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published