我在route.py里面写了一个work function, 它的作用是随机获得一个model(Partition)里面符合要求的对象,然后读取这个对象的数据,从而生成一个动态的表单PostForm()和提供图片的url给template显示。
我的构思是用户填写完按下submit之后,去validate这个form。然后将这个随机对象的id存到一个叫做post的model里面。但是我现在的代码它并不能存当前随机的id,只能够存下一个随机的id。
我确定了是因为每次按submit它都再一次call了work,所以生成了新的random对象,以至于没有办法走进valid_on_submit的条件。我想知道怎么解决这个问题。
代码如下
@app.route('/work', methods=['GET','POST'])
@login_required
def work():
# first of all, return a random partition id
# and check it has been edited by current_user or not
rand_part = Partition.query.filter(Partition.count < 2).order_by(func.random()).first()
col_num = rand_part.getcolumn()
# considering post form as a temporal form
# which may varies due to different partition have different columns
class PostForm(FlaskForm):
pass
for i in range(0,col_num):
setattr (PostForm,'field'+str(i),
StringField('content', validators =[DataRequired()]))
setattr(PostForm, 'submit', SubmitField('Next'))
form = PostForm()
if request.method == 'POST':
if form.validate_on_submit():
templist = ""
for field in form:
if field.type == 'StringField':
templist += ';%s' % field.data
newpost = Post(user_id = current_user.getid(),
part_id = rand_part.getid(),
content = templist)
# commit to db
db.session.add(newpost)
# add editor
partcount = rand_part.getcount()
if partcount == 0:
rand_part.editor1 = current_user.id
elif partcount == 1:
rand_part.editor2 = current_user.id
# increase partition count by 1
rand_part.count = partcount + 1
db.session.commit()
flash('Post has been sent successfully, try next one!', 'success')
return redirect(url_for('work'))
else:
flash('unsuccessful post, sorry')
return redirect(url_for('work'))
return render_template('workPage.html', form = form, part = rand_part)