我想在Flask Admin上执行一些验证。 Flask应用程序连接到后端postgreSQL数据库,并使用SQLAlchemy ORM。
我希望能够在ServerView(flask.ext.admin.contrib.sqla.modelView)中的两个字段(lan_nics,wan_nics)上执行验证检查。基本上我想确保两个字段的总和不大于一定数量。这是表格:
这是test_app代码。我试过按照flask-admin的文档。我添加了一个def,然后在form_args中为验证器字典引用了def ...但它似乎不起作用。目前我只是想确保两个字段的值都小于5。
from flask import Flask
from flask.ext.admin import Admin
from flask.ext.admin.contrib.sqla import ModelView
from flask.ext.sqlalchemy import SQLAlchemy
from wtforms.validators import ValidationError
import psycopg2
# Flask and Flask-SQLAlchemy initialization here
app = Flask(__name__)
db = SQLAlchemy(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:postgres@127.0.0.1/testdb'
app.secret_key = 'MySecret'
conn = psycopg2.connect("dbname='testdb' user='postgres' host='127.0.0.1' password='postgres'")
class Server(db.Model):
__tablename__ = "server"
id = db.Column('server_id', db.Integer, primary_key=True)
model = db.Column('model', db.Unicode)
lan_nics = db.Column('lan_nics', db.Integer)
wan_nics = db.Column('wan_nics', db.Integer)
def __str__(self):
return self.model
class Hardware(db.Model):
__tablename__ = "hardware"
id = db.Column('hardware_id', db.Integer, primary_key=True)
model = db.Column('model', db.Unicode)
max_nics = db.Column('max_nics', db.Integer)
def __str__(self):
return self.model
class ServerView(ModelView):
# Disable model creation
can_create = True
# Override displayed fields
column_list = ('model', 'lan_nics', 'wan_nics')
column_display_all_relations = True
column_searchable_list = ('model')
column_labels = dict(model='Model', lan_nics='LAN Nics', wan_nics='WAN NICs')
form_columns = [ 'model', 'lan_nics', 'wan_nics' ]
def max_allowed(form, field):
if field.data > 5:
raise ValidationError('Max number of interfaces exceeded')
form_args = dict(
lan_nics=dict(validators=[max_allowed]),
wan_nics=dict(validators=[max_allowed])
)
class HardwareView(ModelView):
# Disable model creation
can_create = True
# Override displayed fields
column_list = ('model', 'max_nics')
column_display_all_relations = True
column_searchable_list = ('model')
column_labels = dict(model='Model', max_nics='Max Nics')
form_columns = ['model', 'max_nics' ]
def __str__(self):
return self.model
admin = Admin(app, name="MyApp1")
# Add administrative views here
admin.add_view(ModelView(Server, db.session))
admin.add_view(ModelView(Hardware, db.session))
app.run(port=8000, host="0.0.0.0")
答案 0 :(得分:1)
而不是form_args
,我做了on_model_change
:
class ServerView(ModelView):
...
...
...
def on_model_change(self, form, model, is_created):
hardware = "hardware"
query = "SELECT nics FROM hardware WHERE model = '{}'".format(hardware)
with conn.cursor() as cur:
cur.execute(query)
max_nics = int(cur.fetchone()[0])
if (int(form.lan.data) + int(form.wan.data) > max_nics):
raise ValidationError('Max number of interfaces exceeded!')
else:
return model
答案 1 :(得分:0)
实际上,您的第一种方法有效。您有一个小错误:您应该检查 if field.data > 5:
而不是 if len(field.data) > 5:
。
flask-admin 的文档并没有真正涵盖验证器,但在幕后,它只是将工作委托给 WTForms。他们的文档非常有用:https://wtforms.readthedocs.io/en/3.0.x/validators/ 它还显示了现有的验证器,例如 Length
,您可以改为编写:
from wtforms.validators import Length
form_args = dict(
lan_nics=dict(
validators=[Length(min=5, message='Max number of interfaces exceeded')]
),
)