[英]Flask, WTForms: Error when edit and create form rules are differents
I'm using Flask and WTForms in a web app. 我在网络应用中使用Flask和WTForms。 I have a db.Model, a form and a sqla.ModelView like this:
我有一个db.Model,一个窗体和一个sqla.ModelView这样的:
class Users(db.Model):
__tablename__ = 'users'
id = db.Column(db.INTEGER, primary_key=True)
name = db.Column(db.String, nullable=False)
last_name = db.Column(db.String, nullable=False)
class UsersForm(form.Form):
id = fields.IntegerField('Id')
name = fields.StringField('Name')
last_name = fields.StringField('Last Name')
class UsersAdmin(sqla.ModelView):
column_list = ['id', 'name', 'last_name']
form = UsersForm
form_create_rules = column_list
form_edit_rules = ['name', 'last_name']
But it doesn't work because this error: 但这不起作用,因为此错误:
ValueError: Form <__main__.UsersForm object at 0x7f5039c48710> does not have field name
However, when form_edit_rules is equal to form_create rules, it works perfectly! 但是,当form_edit_rules等于form_create规则时,它可以完美工作!
I found out on flask-admin github issuelist that form_*_rules only affect how form is displayed, but don't affect the form itself. 我在flask-admin github问题列表上发现form _ * _ rules仅影响表单的显示方式,但不影响表单本身。
Creating an instance of a form in flask-admin is not necessary. 无需在flask-admin中创建表单实例。 I would recommend to have your database take care of the id, as it automatically auto-increments.
我建议您让数据库处理id,因为它会自动递增。 In my experience, flask-admin doesn't even show the id field.
以我的经验,flask-admin甚至没有显示id字段。
If you really want to have an editable id field on the create form only, you can make the field readonly on the edit form with the following code: 如果您确实只想在创建表单上有一个可编辑的ID字段,则可以使用以下代码使该字段在编辑表单上为只读:
class UsersAdmin(sqla.ModelView):
def on_form_prefill(self, form, id):
form.id.render_kw = {'readonly': True}
column_list = ['id','name','last_name']
form = UsersForm
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.