我有一个 SQLAlchemy 模型,其中有一个从 HTML 表单填充的整数列(我正在使用 Flask 和 WTForms-alchemy,并且我试图避免在路由中编写自定义代码)。如果用户没有在表单上输入该整数的值,则从表单填充对象的代码最终会尝试为该列放入一个空字符串,并且 MySQL 会抱怨这不是一个整数值。为了帮助人们搜索:我开始遇到的错误Incorrect integer value: '' for column ...。
我不想使用sql_mode=''hack,人们建议这样做是为了让 MySQL 回到旧的行为,每当你给它不正确的数据时就进行猜测,因为我无法控制最终将使用的 MySQL 服务器。
我想要的是类似于默认列规范的东西,除了在没有任何内容传入时指定默认值,我想拦截尝试放入空字符串并将其替换为 None ,我认为这会被转换为当它进入数据库时为 null。
有没有办法在模型定义中做到这一点?我意识到这可能会导致性能下降,但吞吐量在此应用程序中并不是什么大问题。
WTForms已更新为2.3.0具有重大更改。我尝试过调整其他要求,例如werkzeug.1.0.0但还没有成功。有人找到解决办法了吗?
这是堆栈跟踪:
Traceback (most recent call last):
File "/usr/local/bin/celery", line 8, in <module>
sys.exit(main())
File "/usr/local/lib/python3.8/site-packages/celery/__main__.py", line 16, in main
_main()
File "/usr/local/lib/python3.8/site-packages/celery/bin/celery.py", line 322, in main
cmd.execute_from_commandline(argv)
File "/usr/local/lib/python3.8/site-packages/celery/bin/celery.py", line 495, in execute_from_commandline
super(CeleryCommand, self).execute_from_commandline(argv)))
File "/usr/local/lib/python3.8/site-packages/celery/bin/base.py", line 289, in execute_from_commandline
argv = self.setup_app_from_commandline(argv)
File "/usr/local/lib/python3.8/site-packages/celery/bin/base.py", line 509, in setup_app_from_commandline
self.app = self.find_app(app)
File "/usr/local/lib/python3.8/site-packages/celery/bin/base.py", line 531, in find_app
return find_app(app, symbol_by_name=self.symbol_by_name)
File "/usr/local/lib/python3.8/site-packages/celery/app/utils.py", line 373, in find_app
sym = symbol_by_name(app, imp=imp)
File "/usr/local/lib/python3.8/site-packages/celery/bin/base.py", …Run Code Online (Sandbox Code Playgroud) 我想添加一个返回上一页的取消按钮。我的代码是:forms.py:
from flask_wtf import Form
from wtforms import StringField, HiddenField, SubmitField
from wtforms.validators import DataRequired, Length, ValidationError
def _required(form, field):
if not field.raw_data or not field.raw_data[0]:
raise ValidationError('Field is required')
class OrganisationForm(Form):
id = HiddenField('id', default="-1")
name = StringField('name', validators=[DataRequired()])
manager_name = StringField('manager_name')
address = StringField('address', validators=[DataRequired()])
city = StringField('city', validators=[DataRequired()])
postal_code = StringField('postal_code', validators=[DataRequired(), Length(max=16)])
province = StringField('province', validators=[Length(max=2, message="Can't exceed 2 characters")])
country = StringField('country', validators=[DataRequired()])
submit = SubmitField('Add')
cancel = SubmitField('Cancel')
Run Code Online (Sandbox Code Playgroud)
和模板页面:
{% block content %}
<div …Run Code Online (Sandbox Code Playgroud) 我的输入格式很奇怪,但根据规范:

用户应在4个字段(!)中输入ID,其中id为460 000 005 001,其中46是国家代码,右边部分是用户的appengine ID.现在我想在此字段中添加验证,但我无法使用wtforms进行验证.这是我的表单类:
class RegisterWTForm(Form):
soc_sec = TextField(_('Soc security number'), [validators.Regexp('^[0-9]+$',
message=_('This is not a social security number, please see the example and try again'
)), validators.Required(message=_('Social security number is required')), unique_soc_sec], widget=MyTextInput())
email = TextField(_('Email'),
[validators.Required(message=_('Email is required'
)),
validators.Email(message=_('Your email is invalid'
))], widget=MyTextInput())
def validate_soc_sec(form, field):
if len(field.data) != 10:
raise ValidationError(_('Soc sec must be 10 characters'
))
def validate_email(form, field):
if len(field.data) > 60:
raise ValidationError(_('Email must be less than 60 characters'
)) …Run Code Online (Sandbox Code Playgroud) 我正在使用Flask-WTF表单,我有以下代码:
在forms.py中
class DealForm( Form ):
country = SelectField( 'Country' )
Run Code Online (Sandbox Code Playgroud)
在main.py中
if not form.validate_on_submit():
form = DealForm()
form.country.choices = [('us','USA'),('gb','Great Britain'),('ru','Russia')]
return render_template( 'index.html', user = current_user, form = form )
else:
return render_template( 'index.html', form = form )
Run Code Online (Sandbox Code Playgroud)
我从POST返回时出错,因为country.choices是None我做错了什么?
我正在为代表账单的对象制作一个crud接口,如水费单,电费单等.
我正在使用sqlalchemy处理数据,使用wtforms来处理表单,并使用flask来处理它.
以下是我的路线看起来像是用来编辑现有账单的表格:
@app.route('/edit_bill/<int:bill_id>', methods = ['GET'])
def edit_bill(bill_id):
s = Session()
bill = s.query(Bill).filter_by(id=bill_id).first()
form = BillForm(obj=Bill)
return render_template('edit_bill.html', form = form)
Run Code Online (Sandbox Code Playgroud)
使用wtforms,我将bill对象传递给BillForm构造函数,确保表示要编辑的帐单的数据填充到表单中.
这就是它窒息的地方.这是例外:
AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with Bill.date_due has an attribute 'strftime'
Run Code Online (Sandbox Code Playgroud)
现在,我已经深入了解python shell并查询了一个帐单,以确保date_due上有一个datetime.date对象,就是这样.我使用Jinja来构建我的前端,所以我考虑创建一个模板过滤器,但我不知道如何使用wtforms,看起来sqlalchemy无论如何都是窒息.
那么它做什么?我非常有信心我只需要弄清楚如何将该datetime.date对象转换为字符串,但我不知道该怎么做.
HALP.谢谢!
编辑:这是BillForm类:
class BillForm(Form):
id = HiddenField()
name = TextField(u'Name:', [validators.required()])
pay_to = TextField(u'Pay To:',[validators.required()])
date_due = DateField(u'Date Due:',[validators.required()])
amount_due = IntegerField(u'Amount Due:', [validators.required()])
date_late = DateField(u'Late After:',[validators.required()])
amount_late = IntegerField(u'Late Amount:', [validators.required()])
date_termination …Run Code Online (Sandbox Code Playgroud) 这可能非常简单.但我正在使用WTForms,并希望将字段的值设置为我从数据库中提取的变量.但它不是显示动态变量,而是显示变量名称.
{{ form.question.label }}
{{ form.question(value="{{ q.question }}") }}
{{ form.slug.label }}
{{ form.slug(value="{{ q.slug }}") }}
Run Code Online (Sandbox Code Playgroud)
所以在现场它说"{{q.question}}"而不是"生命的意义是什么?"之类的东西.
有没有办法在Jinja中显示嵌套变量?或者我还有其他方法可以解决这个问题吗?任何帮助表示赞赏!
我有一个带有多个链接的页面,可以将用户重定向到不同的页面.我认为使用表单会更好,所以我定义了一个Form具有多个的WTForms SubmitFields.如何确定单击了哪个按钮并根据该按钮进行重定向?
class MainForm(Form):
user_stats = SubmitField('User Stats')
room_stats = SubmitField('Room Stats')
@main.route('/')
@login_required
def index():
form = MainForm()
return render_template('index.html', form=form)
Run Code Online (Sandbox Code Playgroud)
<form action="#" method="post">
{{ wtf.quick_form(form) }}
</form>
Run Code Online (Sandbox Code Playgroud) 我正在使用Flask-WTForms创建一个表单.
我正在使用BooleanField,以便用户可以表明他们同意条款.
我无法在提交时验证BooleanField以确保它已被检查.我尝试使用Required(),DataRequired()和自定义验证,但在每种情况下我都没有收到验证错误.
以下是该应用程序的细节:
from flask import Flask, render_template, session, redirect, url_for, flash
from flask_wtf import Form
from wtforms import BooleanField, SubmitField
from wtforms.validators import Required, DataRequired
from flask_bootstrap import Bootstrap
app = Flask(__name__)
app.config['SECRET_KEY'] = 'impossibletoknow'
bootstrap = Bootstrap(app)
class AgreeForm(Form):
agreement = BooleanField('I agree.', validators=[DataRequired()])
submit = SubmitField('Submit')
@app.route('/', methods=['GET', 'POST'])
def index():
form = AgreeForm()
if form.validate_on_submit():
agreement = form.agreement.data
if agreement is True:
flash('You agreed!')
return redirect(url_for('index', form=form))
form.agreement.data = None
agreement = False
return render_template('index.html', …Run Code Online (Sandbox Code Playgroud) 我在表单验证方面遇到了麻烦.国家/地区列表生成正确,以前的表单工作正常.它只会在POST请求中中断.
这是我的forms.py:
from wtforms import Form, BooleanField, SelectField, \
StringField, PasswordField, SubmitField, validators, \
RadioField
from ..models import User
from pycountry import countries
...
## Account settings
# We get all COUNTRIES
COUNTRIES = [(c.name, c.name) for c in countries]
# edit profile
class ProfileForm(Form):
username = StringField('name',[validators.Length(min=1, max=120), validators.InputRequired])
email = StringField('email', [validators.Length(min=6, max=120), validators.Email()])
company = StringField('name',[validators.Length(min=1, max=120)])
country = SelectField('country', choices=COUNTRIES)
news = BooleanField('news')
Run Code Online (Sandbox Code Playgroud)
这是观点:
@user.route('/profile/', methods=['GET', 'POST'])
@login_required
def profile():
userid = current_user.get_id()
user = User.query.filter_by(id=userid).first_or_404() …Run Code Online (Sandbox Code Playgroud)