Python: Editable Table with Flask and Jinja

早过忘川 提交于 2021-02-10 14:59:18

问题


I'm working on a Flask web server. What is the best way to read a table from my SQL database, display it editable in the users webbrowser via HTML and after the user submits get the changes and write it back to the sql database?

CRUD on the database is the easiest thing. I can also display the table in the browser with Jinja, but non-editable. But I absolutly have no idea have to display the data in such a way that the user can edit cells, or delete and add rows. I also don't know how I send the table back to Flask.

I personally think that this is a common problem, but I didn't found any working solutions. So can I achieve this?


回答1:


The first hit that I got for an editable grid is: https://www.npmjs.com/package/editable-grid

The examples are at https://www.npmjs.com/package/editable-grid#view-demos-with-implementation-code.

In particular the example Editable cells is the one, that I think you need. The code for an editable table according to the example would be as follows. In order to have the data persist to database you would need to add a button that on click, sends the data of the editable table.

function (el) {
  var grid = new Grid({
      el: el,
      stateManager: {
          isEditable: function (rowId, colId) {
              if (colId === 'readOnly') { return false; }
              return true;
          }
      },
      columns: [
          { id: 'readOnly', title: 'Title', width: '20%' },
          { id: 'string', title: 'String', width: '20%' },
          { id: 'cost', title: 'Cost', width: '20%', type: 'cost' },
          { id: 'percent', title: 'Percent', width: '20%', type: 'percent' },
          { id: 'date', title: 'Date', width: '20%', type: 'date' }
      ],
      data: [
          { id: 'id-1', readOnly: 'Non editable field', string: 'Hello World', cost: 1000.23, percent: 0.45, date: '2014-03-27' },
          { id: 'id-2', readOnly: 'Non editable field', string: 'Good Morning', percent: 0.45 },
          { id: 'id-3', readOnly: 'Non editable field', cost: 1000.23, percent: 0.45, date: '2014-04-27' }
      ]
  });
  grid.render();
  grid.on('editable-value-updated', function (/*obj*/) {
  });
}

You can likely get the current values of the cells by using the grid variables. If that is not possible, then you can listen to the events like

grid.on('editable-value-updated', function(params) {});
grid.on('editable-new-row-value-changed', function(newObj, colId) {});
grid.on('editable-new-row', function(newObj) {});

to get the changes to data and store those in a temporary object.

P.S. Note that you don't need to do npm install to get the library, you can use the standalone versions.

  1. http://skinnybrit51.com/editable-grid/dist/editable_grid.min.js
  2. http://skinnybrit51.com/editable-grid/dist/editable_grid.min.css

Both the js and css files are required.




回答2:


Suppose you have a model :

class Student(db.Model):
    name = db.Column(db.String(80), unique=True, nullable=False, primary_key=True)

    def __repr__(self):
        return "<Name: {}>".format(self.name)

You have already stored it in database :

@app.route("/", methods=["GET", "POST"])
def home():
    if request.form:
        student = Student(name=request.form.get("name"))
        db.session.add(student)
        db.session.commit()
    return render_template("home.html")

HTML goes like this :

<html>
  <body>
    <h1>Add Student</h1>
    <form method="POST" action="/">
        <input type="text" name="name">
        <input type="submit" value="Add">
    </form>
{% for student in students %}
  <p>{{student.name}}</p>
  <form method="POST" action="./update">
    <input type="hidden" value="{{student.name}}" name="beforename">
    <input type="text" value="{{student.name}}" name="updatedname">
    <input type="submit" value="Update">
  </form>
{% endfor %}
  </body>
</html>

and routes.py will be :

@app.route("/update", methods=["POST"])
def update():
    updatedname = request.form.get("updatedname")
    beforename = request.form.get("beforename")
    student = Student.query.filter_by(name=updatedname).first()
    student.name = updatedname
    db.session.commit()
    return redirect("/")


来源:https://stackoverflow.com/questions/60934135/python-editable-table-with-flask-and-jinja

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!