Python Flask admin如何在行旁边添加按钮
我使用Flask和Flask admin来管理学费支付应用程序 Flask Admin通过我在models.py上声明的SQLAlchemy自动生成表行 这是我的桌子的图像: 现在,我想在每张总账单旁边设置一个按钮,用于结账 我知道如何使用ModelView提供的column\u list方法添加列,因为我尝试使用下面的代码:Python Flask admin如何在行旁边添加按钮,python,flask,flask-sqlalchemy,flask-login,flask-admin,Python,Flask,Flask Sqlalchemy,Flask Login,Flask Admin,我使用Flask和Flask admin来管理学费支付应用程序 Flask Admin通过我在models.py上声明的SQLAlchemy自动生成表行 这是我的桌子的图像: 现在,我想在每张总账单旁边设置一个按钮,用于结账 我知道如何使用ModelView提供的column\u list方法添加列,因为我尝试使用下面的代码: column_list = ('student_id', 'total_bill', 'Pay Now') 它将提供如下视图显示: 现在我希望列立即付款中的每一行都有一
column_list = ('student_id', 'total_bill', 'Pay Now')
它将提供如下视图显示:
现在我希望列立即付款中的每一行都有一个按钮,就像我用HTML手动编码一样,如下所示:
每行都有一个checkout按钮,正如我上面提到的,这个目的是为了checkout按钮
那么,如何做到这一点呢?),我们将非常感谢您提供的任何帮助您可以用任何方式呈现专栏
Github上的示例代码
例如,每行“Checkout”按钮都可以呈现为一个HTML表单,表单中有一个提交按钮,学生id呈现为一个隐藏字段
下面的简单示例(Python2.7)中,所有文件都位于根目录中views.py
包含重要的代码,其余的代码很简单
ClassStudentView
定义了一个方法\u format\u pay\u now
,如果模型的是付费的
值是True
或者是HTML表单,则该方法要么呈现字符串“Paid”
类StudentView
还通过方法checkout\u view
公开一个路由'/admin/student/checkout'
,以处理提交的表单。在此特定实例中,is\u paid
列被设置为True,列表视图被重新呈现
视图.py
from flask import redirect, flash, url_for
from flask_admin import expose
from flask_admin.contrib import sqla
from flask_admin.helpers import get_form_data
from flask_admin.babel import gettext
from markupsafe import Markup
class StudentView(sqla.ModelView):
page_size = 5
column_list = ('id', 'cost', 'Pay Now')
column_editable_list = ['cost']
# override the column labels
column_labels = {
'id': 'Student ID',
'cost': 'Total Bill',
}
def _format_pay_now(view, context, model, name):
if model.is_paid:
return 'Paid'
# render a form with a submit button for student, include a hidden field for the student id
# note how checkout_view method is exposed as a route below
checkout_url = url_for('.checkout_view')
_html = '''
<form action="{checkout_url}" method="POST">
<input id="student_id" name="student_id" type="hidden" value="{student_id}">
<button type='submit'>Checkout</button>
</form
'''.format(checkout_url=checkout_url, student_id=model.id)
return Markup(_html)
column_formatters = {
'Pay Now': _format_pay_now
}
@expose('checkout', methods=['POST'])
def checkout_view(self):
return_url = self.get_url('.index_view')
form = get_form_data()
if not form:
flash(gettext('Could not get form from request.'), 'error')
return redirect(return_url)
# Form is an ImmutableMultiDict
student_id = form['student_id']
# Get the model from the database
model = self.get_one(student_id)
if model is None:
flash(gettext('Student not not found.'), 'error')
return redirect(return_url)
# process the model
model.is_paid = True
try:
self.session.commit()
flash(gettext('Student, ID: {student_id}, set as paid'.format(student_id=student_id)))
except Exception as ex:
if not self.handle_view_exception(ex):
raise
flash(gettext('Failed to set student, ID: {student_id}, as paid'.format(student_id=student_id), error=str(ex)), 'error')
return redirect(return_url)
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Student(db.Model):
id = db.Column(db.Integer, primary_key=True)
cost = db.Column(db.Integer(), nullable=False)
is_paid = db.Column(db.Boolean(), nullable=False)
def __str__(self):
return unicode(self).encode('utf-8')
def __unicode__(self):
return "ID: {id}; Cost : {cost}".format(id=self.id, cost=self.cost)
from flask import Flask
from flask_admin import Admin
from models import db, Student
from commands import create_database
app = Flask(__name__)
# Create dummy secrey key so we can use sessions
app.config['SECRET_KEY'] = '123456790'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
# Create in-memory database
app.config['DATABASE_FILE'] = 'sample_db.sqlite'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + app.config['DATABASE_FILE']
db.init_app(app)
app.cli.add_command(create_database)
# Flask views
@app.route('/')
def index():
return '<a href="/admin/">Click me to get to Admin!</a>'
from views import StudentView
admin = Admin(app, template_mode="bootstrap3")
admin.add_view(StudentView(Student, db.session))
if __name__ == '__main__':
app.run()
命令.py
from flask import redirect, flash, url_for
from flask_admin import expose
from flask_admin.contrib import sqla
from flask_admin.helpers import get_form_data
from flask_admin.babel import gettext
from markupsafe import Markup
class StudentView(sqla.ModelView):
page_size = 5
column_list = ('id', 'cost', 'Pay Now')
column_editable_list = ['cost']
# override the column labels
column_labels = {
'id': 'Student ID',
'cost': 'Total Bill',
}
def _format_pay_now(view, context, model, name):
if model.is_paid:
return 'Paid'
# render a form with a submit button for student, include a hidden field for the student id
# note how checkout_view method is exposed as a route below
checkout_url = url_for('.checkout_view')
_html = '''
<form action="{checkout_url}" method="POST">
<input id="student_id" name="student_id" type="hidden" value="{student_id}">
<button type='submit'>Checkout</button>
</form
'''.format(checkout_url=checkout_url, student_id=model.id)
return Markup(_html)
column_formatters = {
'Pay Now': _format_pay_now
}
@expose('checkout', methods=['POST'])
def checkout_view(self):
return_url = self.get_url('.index_view')
form = get_form_data()
if not form:
flash(gettext('Could not get form from request.'), 'error')
return redirect(return_url)
# Form is an ImmutableMultiDict
student_id = form['student_id']
# Get the model from the database
model = self.get_one(student_id)
if model is None:
flash(gettext('Student not not found.'), 'error')
return redirect(return_url)
# process the model
model.is_paid = True
try:
self.session.commit()
flash(gettext('Student, ID: {student_id}, set as paid'.format(student_id=student_id)))
except Exception as ex:
if not self.handle_view_exception(ex):
raise
flash(gettext('Failed to set student, ID: {student_id}, as paid'.format(student_id=student_id), error=str(ex)), 'error')
return redirect(return_url)
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Student(db.Model):
id = db.Column(db.Integer, primary_key=True)
cost = db.Column(db.Integer(), nullable=False)
is_paid = db.Column(db.Boolean(), nullable=False)
def __str__(self):
return unicode(self).encode('utf-8')
def __unicode__(self):
return "ID: {id}; Cost : {cost}".format(id=self.id, cost=self.cost)
from flask import Flask
from flask_admin import Admin
from models import db, Student
from commands import create_database
app = Flask(__name__)
# Create dummy secrey key so we can use sessions
app.config['SECRET_KEY'] = '123456790'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
# Create in-memory database
app.config['DATABASE_FILE'] = 'sample_db.sqlite'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + app.config['DATABASE_FILE']
db.init_app(app)
app.cli.add_command(create_database)
# Flask views
@app.route('/')
def index():
return '<a href="/admin/">Click me to get to Admin!</a>'
from views import StudentView
admin = Admin(app, template_mode="bootstrap3")
admin.add_view(StudentView(Student, db.session))
if __name__ == '__main__':
app.run()
使用flask create database
生成SQLite数据库
import random
from flask.cli import click, with_appcontext
from models import db, Student
@click.command('create-database')
@with_appcontext
def create_database():
# Create 100 students
db.drop_all()
db.create_all()
for _ in range(0, 100):
_project = Student(
cost=random.randrange(10, 200),
is_paid=False
)
db.session.add(_project)
db.session.commit()
app.py
from flask import redirect, flash, url_for
from flask_admin import expose
from flask_admin.contrib import sqla
from flask_admin.helpers import get_form_data
from flask_admin.babel import gettext
from markupsafe import Markup
class StudentView(sqla.ModelView):
page_size = 5
column_list = ('id', 'cost', 'Pay Now')
column_editable_list = ['cost']
# override the column labels
column_labels = {
'id': 'Student ID',
'cost': 'Total Bill',
}
def _format_pay_now(view, context, model, name):
if model.is_paid:
return 'Paid'
# render a form with a submit button for student, include a hidden field for the student id
# note how checkout_view method is exposed as a route below
checkout_url = url_for('.checkout_view')
_html = '''
<form action="{checkout_url}" method="POST">
<input id="student_id" name="student_id" type="hidden" value="{student_id}">
<button type='submit'>Checkout</button>
</form
'''.format(checkout_url=checkout_url, student_id=model.id)
return Markup(_html)
column_formatters = {
'Pay Now': _format_pay_now
}
@expose('checkout', methods=['POST'])
def checkout_view(self):
return_url = self.get_url('.index_view')
form = get_form_data()
if not form:
flash(gettext('Could not get form from request.'), 'error')
return redirect(return_url)
# Form is an ImmutableMultiDict
student_id = form['student_id']
# Get the model from the database
model = self.get_one(student_id)
if model is None:
flash(gettext('Student not not found.'), 'error')
return redirect(return_url)
# process the model
model.is_paid = True
try:
self.session.commit()
flash(gettext('Student, ID: {student_id}, set as paid'.format(student_id=student_id)))
except Exception as ex:
if not self.handle_view_exception(ex):
raise
flash(gettext('Failed to set student, ID: {student_id}, as paid'.format(student_id=student_id), error=str(ex)), 'error')
return redirect(return_url)
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Student(db.Model):
id = db.Column(db.Integer, primary_key=True)
cost = db.Column(db.Integer(), nullable=False)
is_paid = db.Column(db.Boolean(), nullable=False)
def __str__(self):
return unicode(self).encode('utf-8')
def __unicode__(self):
return "ID: {id}; Cost : {cost}".format(id=self.id, cost=self.cost)
from flask import Flask
from flask_admin import Admin
from models import db, Student
from commands import create_database
app = Flask(__name__)
# Create dummy secrey key so we can use sessions
app.config['SECRET_KEY'] = '123456790'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
# Create in-memory database
app.config['DATABASE_FILE'] = 'sample_db.sqlite'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + app.config['DATABASE_FILE']
db.init_app(app)
app.cli.add_command(create_database)
# Flask views
@app.route('/')
def index():
return '<a href="/admin/">Click me to get to Admin!</a>'
from views import StudentView
admin = Admin(app, template_mode="bootstrap3")
admin.add_view(StudentView(Student, db.session))
if __name__ == '__main__':
app.run()
您可以像这样添加自定义行操作按钮。它可以给它一个自定义的布局,但它与您正在寻找的略有不同。