我以前使用过烧瓶,并且已经进行了有效的表单验证,但由于某种原因,它不适用于我的新应用程序。这是表单的基本代码。
from flask.ext.wtf import Form, TextField, TextAreaField, SubmitField, validators,ValidationError
class subReddit(Form):
subreddit = TextField('subreddit', [validators.Required('enter valid subreddit')])
next = SubmitField('next')
change = SubmitField('change')
user = TextField('user', [validators.Required('enter valid user')])
fetch = SubmitField('fetch comments')
我有 subreddit 作为验证字段,所以如果它是空的,我希望它抛出错误并重新加载页面。
的HTML:
<form class='sub' action="{{ url_for('sr') }}" method='post'>
{{ form.hidden_tag() }}
<p>
if you want to enter more than one subreddit, use the + symbol, like this:
funny+pics+cringepics
<p>
<br/>
{% for error in form.subreddit.errors %}
<p>{{error}}</p>
{% endfor %}
{{form.subreddit.label}}
{{form.subreddit}}
{{form.change}}
</form>
我的 routes.py 中也有 CSRF_ENABLED=True 。我错过了什么?当我将 subredditfield 留空并单击更改时,它只是重新加载页面,没有错误。这是一个问题,因为该字段中的任何内容都将记录在我的数据库中,并且不能为空。
编辑
@app.route('/index',methods=['GET','POST'])
@app.route('/',methods=['GET','POST'])
def index():
form = subReddit()
rand = random.randint(0,99)
sr = g.db.execute('select sr from subreddit')
srr = sr.fetchone()[0]
r = requests.get('http://www.reddit.com/r/{subreddit}.json?limit=100'.format(subreddit=srr))
j = json.loads(r.content)
pic = j['data']['children'][rand]['data']['url']
title = None
if form.validate_on_submit():
g.db.execute("UPDATE subreddit SET sr=(?)", [form.subreddit.data])
print 'validate '
if j['data']['children'][rand]['data']['url']:
print 'pic real'
sr = g.db.execute('select sr from subreddit')
srr = sr.fetchone()[0]
r = requests.get('http://www.reddit.com/r/{subreddit}.json?limit=100'.format(subreddit=srr))
pic = j['data']['children'][rand]['data']['url']
title = str(j['data']['children'][rand]['data']['title']).decode('utf-8')
return render_template('index.html',form=form,srr=srr,pic=pic,title=title)
else:
print 'not valid pic'
return render_template('index.html',form=form,srr=srr,pic=pic)
else:
print 'not valid submit'
return render_template('index.html',form=form,srr=srr,pic=pic)
return render_template('index.html',form=form,srr=srr,pic=pic)