我正在使用Flask与Flask-WTForms,我正在编写一个管理页面,可以更新用户的值 - 包括密码.
我正在使用我用于注册的相同表单页面,但由于不必更新密码,我不想要它.使用Flask-WTForms进行此操作的正确方法是什么?
我已经进入UserForm了forms.py,我正在考虑制作一个自定义验证器,并且有一个文件级require_password选项可以覆盖默认检查.我是WTForms的新手,对Flask来说有点新鲜.
我想要使用Flask的"SubmitField"
<button type="submit" title="Save this form"><span>Save</span></button>
Run Code Online (Sandbox Code Playgroud)
代替:
<input type="submit" title="Save this form" />
Run Code Online (Sandbox Code Playgroud)
我在模板中打印出来:
{{ field(class=css_class, title=field.description, **kwargs) }}
Run Code Online (Sandbox Code Playgroud)
我猜我必须以某种方式修改SubmitInput(SubmitField背后的小部件),但我不确定如何做到这一点,我是否必须修改__html __()?
编辑:
from flask.ext.wtf import Required, Length, EqualTo, Field, TextInput
from flask import Markup
class InlineButtonWidget(object):
html = """
<button type="submit" title="%s"><span>%s</span></button>
"""
def __init__(self, input_type='submit'):
self.input_type = input_type
def __call__(self, field, **kwargs):
kwargs.setdefault('id', field.id)
kwargs.setdefault('type', self.input_type)
if 'value' not in kwargs:
kwargs['value'] = field._value()
return HTMLString(self.html % (field.name, field.label ))
class InlineButton(Field):
widget = InlineButtonWidget()
def _value(self):
if self.data: …Run Code Online (Sandbox Code Playgroud) 我用以下方式定义了一个表单:
class LoginForm(Form):
login = EmailField(u'Email address', [required(), length(min=5, max=2048), validators.Email()])
password = PasswordField(u'Password', [required(), length(min=6, max=50)])
next = HiddenField()
remember = BooleanField('Remember me')
submit = SubmitField('Login')
Run Code Online (Sandbox Code Playgroud)
然后我在Jinja2中编写一个通用宏来渲染表单字段,我想做的事情如下:
{% if field.is_required() %}
{{ field.label(class_='required') }}
{% else %}
{{ field.label() }}
{% endif %}
Run Code Online (Sandbox Code Playgroud)
那么......有没有办法看看是否需要一个字段?
sqlalchemy.exc.InterfaceError: <unprintable InterfaceError object>我正在尝试 Flask,但在提交 wtforms 时遇到错误。模型类是:
class Post(db.Model):
__tablename__ = 'blog_posts'
id = db.Column(db.Integer, unique=True, primary_key=True)
title = db.Column(db.String(50), unique=False)
content = db.Column(db.Text, unique=False)
user_id = db.Column(db.String, db.ForeignKey('users.username'))
@staticmethod
def post_new_entry(title, content, user_id):
""" Post new entry to database """
new_post = Post(title=title, content=content, user_id=user_id)
db.session.add(new_post)
db.session.commit()
return new_post
def __repr__(self):
return 'PostID {}: {} by {}'.format(self.id, self.title, self.user_id)
Run Code Online (Sandbox Code Playgroud)
对于我的表格,我有以下内容:
class PostForm(Form):
title = StringField('Title', validators=[DataRequired(), Length(10, 65)])
post_content = TextAreaField('Content', validators=[DataRequired(), Length(50, 500)])
submit = SubmitField('Publish Post') …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 Flask-Bootstrap 渲染 WTF 表单quick_form。form但是,即使我将其传递给 ,我也会收到未定义的错误render_template。为什么这不起作用?
File "/home/eron/anaconda/lib/python2.7/site-packages/flask_bootstrap/templates/bootstrap/wtf.html", line 190, in template
{{ form.hidden_tag() }}
File "/home/eron/anaconda/lib/python2.7/site-packages/jinja2/environment.py", line 397, in getattr
return getattr(obj, attribute)
UndefinedError: 'form' is undefined
Run Code Online (Sandbox Code Playgroud)
from flask.ext.wtf import Form
class NameForm(Form):
name = StringField('Login', validators=[Required()])
submit = SubmitField('Submit')
@app.route('/base', methods=['GET','POST'])
def index():
name = None
form = NameForm()
if form.validate_on_submit():
name = form.name.data
session['name'] = form.name.data
return redirect(url_for('base'))
return render_template('base.html', form=form)
Run Code Online (Sandbox Code Playgroud)
File "/home/eron/anaconda/lib/python2.7/site-packages/flask_bootstrap/templates/bootstrap/wtf.html", line 190, in template
{{ form.hidden_tag() }}
File …Run Code Online (Sandbox Code Playgroud) 这是我的代码:
class ChangeOfficialForm(Form):
is_official = SelectField(
'Officially Approved',
choices=[(True, 'Yes'), (False, 'No')],
validators=[DataRequired()],
coerce=bool
)
submit = SubmitField('Update status')
Run Code Online (Sandbox Code Playgroud)
出于某种原因,is_official.data总是如此True.我怀疑我误解了胁迫是如何起作用的.
我正在尝试使用Bootstrap-CSS和水平显示单选按钮Flask-WTForms.据我所知,我需要使用Bootstrap类class_="radio-inline"来实现这一目标.我试过了,我得到的就是这个:
其中,单选按钮是垂直组织的,令人沮丧.
Flask WTForm代码:
from flask.ext.wtf import Form
import csv
import os
import buildHome as bh
from wtforms import TextField, RadioField, TextAreaField, SubmitField, validators, BooleanField
class ContactForm(Form):
firstName = TextField("First name", [validators.Required("Please enter your first name.")])
lastName = TextField("Last name", [validators.Required("Please enter your last name.")])
#name = TextField("Name", [validators.Required("Please enter your name.")])
email = TextField("Email", [validators.Required("Please enter your email address."), validators.Email("Please enter your email address.")])
node_1 = BooleanField("Joan Johnson (Buckridge Inc)")
direction_1 = RadioField('', …Run Code Online (Sandbox Code Playgroud) 我正在将 Django 应用程序移植到 Flask,但在最后一步中遇到了此错误:将其配置为在 nginx/gunicorn 后面运行。在 Django 中,这会引发类似的错误消息。要消除 Django 中的此错误,您只需添加ALLOWED_HOSTS到设置中,但我在 Flask_wtf.csrf 的源代码中找不到任何类似的内容
当我填写POST表格并提交时,它失败并显示Bad Request Referrer checking failed - origin does not match.。
flask_wtf.csrf.CsrfProtect 谷歌搜索该字符串,我找到了here的源代码。这是referrer针对进行检查host。自己手动执行该代码,我可以看到它将我的 nginx 的主机:端口与我的 Gunicorn 的主机:端口进行比较,并且它失败了,因为我的 Gunicorn 端口与 nginx 位于不同的端口上。
这是该文件中的相关源代码,其中有我的注释作为注释
# Presumably, good_referrer is Gunicorn, request.referrer is Nginx
# In Django's csrf source code, there is a list of ALLOWED_HOSTS to check against, instead
def protect(self):
#...
# If I change WTF_CSRF_SSL_STRICT to false, it doesn't …Run Code Online (Sandbox Code Playgroud) 是否可以在离开字段后提交之前验证 WTForm 字段?例如,输入用户名后,会验证该字段以查看其是否可用并显示复选标记,然后用户单击“提交”。
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)