jQuery ui sortable - save to database with Python/Flask/SQLite

人盡茶涼 提交于 2020-01-03 06:33:43

问题


i need a drag and drop effect, just finding the jQuery sortable the most viable and easy solution, but I would like to save the positions after reordered. Using php/sqlite i can do this but as I am using the framework flask the solution would have to be in python. I came to this code searching here

html:

$(function() {
    var $sortables = $("#sortMe").sortable({
        stop: function() {
            var sortedItems = $sortables.sortable("toArray");
        }
    });
});

py:

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'

class Sortable(db.Model):
    __tablename__ = 'sortables'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    data = db.Column(db.String)

    def __init__(self, data):
        self.data = data

@app.route("/saveorder", methods=['GET', 'POST'])
def save_order():
    if request.method == "POST":

edit.

now, i got this

html:

    $(function() {
        $('#sortMe').sortable({
            update: function(event, ui) {
                var postData = $(this).sortable('serialize');
                console.log(postData);

                $.ajax({
                    url: '/saveorder',
                    type: 'POST',
                    contentType: 'application/json',
                    dataType: 'json',
                    data: JSON.stringify({list: postData}),
                    success: function (ret) {
                        alert('JSON posted: ' + JSON.stringify(ret));
                    }
                });
            }
        });
    });

py:

@app.route("/saveorder", methods=['GET', 'POST'])
def saveorder():
    json = request.json
    print(json)

    return jsonify(json)

回答1:


i found the soluction

https://github.com/h01000110/sortable-flask

app.py

from flask import Flask, render_template, request, jsonify
from flask_sqlalchemy import SQLAlchemy


app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)


class Sortable(db.Model):
    __tablename__ = 'sortables'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    data = db.Column(db.String)

    def __init__(self, data):
        self.data = data


db.create_all()


@app.route('/')
def index():
    sort = Sortable.query.filter_by(id=1).first()
    ordem = str(sort.data)
    return render_template('index.html', sort=sort, ordem=ordem)


@app.route('/post', methods=['GET', 'POST'])
def post():
    json = request.json
    x = json.replace('item[]=', ',')
    y = x.replace('&,', '')
    final = y.replace(',', '')

    sort = Sortable.query.filter_by(id=1).first()
    sort.data = final

    db.session.commit()

    return jsonify(final)


if __name__ == '__main__':
    app.run(debug=True)

index.html

<html>
  <head>
    <title>Flask example</title>
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script>
        $(function(){
            $('#sortMe').sortable({
                update: function(event, ui) {
                    var postData = $(this).sortable('serialize');

                    $.ajax({
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify(postData),
                        dataType: 'json',
                        url: '/post'
                    });
                }
            });
        });
    </script>
  </head>
  <body>
    <ul id="sortMe">
    {% for i in ordem %}
        <li id="item_{{ i }}">item {{ i }}</li>
    {% endfor %}
    </ul>
  </body>
</html>


来源:https://stackoverflow.com/questions/40294705/jquery-ui-sortable-save-to-database-with-python-flask-sqlite

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