Dynamic Table Columns Issue


There is no issue with the data being passed to Flask via the Jscript, that seems to be fine. But actually using the columns with ‘spAdvertisedProduct.query.with_entities’ doesn’t seem to work.

My goal is to change the column names/values dynamically using checkboxes. The tables in Flask are already showing dynamic headers/rows using JINJA. This would just be a nice to have on top of that.

My code:
Python –

@main.route('/update-columns', methods=['POST'])
def data():
    # Retrieve the list of selected columns from the submitted form
    res = request.json
    table_data = res['columns']
    #pre_res = ["spAdvertisedProduct." + sub for sub in table_data]
    selected_columns = [text(col) for col in table_data]
    data = spAdvertisedProduct.query.with_entities(*selected_columns).all()

    # Retrieve the data from the database, selecting only the desired columns
    # Render the table in the template, using only the selected columns
    return render_template('adsdash.html', column_names=table_data, data=data)

JScript –

var confirmButton = document.getElementById('confirmColumns');
confirmButton.addEventListener('click', function() {
    var checkboxes = document.querySelectorAll('input[type=checkbox]:checked[id^="columncheck_"]');
    var selectedColumns = Array.from(checkboxes, function(checkbox) {
    var label = checkbox.closest('label');
    if (label !== null) {
        return label.textContent.trim();
    return null;
}).filter(function(textContent) {
    return textContent !== null;

fetch('/update-columns', {
  method: 'POST',
  body: JSON.stringify({ columns: selectedColumns }),
  headers: {
    'Content-Type': 'application/json'

.then(function(response) {
  if (!response.ok) {
    throw new Error('Network response was not ok');
  return response.text();
.then(function(responseText) {
.catch(function(error) {
  console.error('There was a problem with the fetch operation:', error);

When attempting to change the columns selected in Flask using sqlAlchemy, I receive the following:

sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (1109, "Unknown table 'spAdvertisedProduct' in field list")

I have attempted removing ‘spAdvertisedProduct.’ as a prefix, which returned the following:

(1054, "Unknown column 'campaignId' in 'field list'")

Asked By: OPT



Changing the line :

data = spAdvertisedProduct.query.with_entities(*selected_columns).all()


table_data = spAdvertisedProduct.query.with_entities(*[getattr(spAdvertisedProduct, column) for column in selected_columns]).all()

resolves the issue.

Answered By: OPT
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.