报错截图如下
通过debug信息定位到Form表单中出现问题。下面的for category in Category.query.order_by(Category.name).all()
迭代不出数据。但是Category模型中确实有数据的。参考下下图
class PostForm(FlaskForm):
title = StringField('Title', validators=[DataRequired(), Length(1, 60)])
category = SelectField('Category', coerce=int, default=1)
body = CKEditorField('Body', validators=[DataRequired()])
submit = SubmitField()
# 构造函数
def __int__(self, *args, **kwargs):
super(PostForm, self).__init__(*args, **kwargs)
self.category.choices = [(category.id, category.name) \
for category in Category.query.order_by(Category.name).all()]
在shell下查询Category模型中name值,如下
Instance: /root/bluelog/instance
>>> category=Category.query.get(3)
>>> category.name
'Devin Jenkins'
帮忙看下我分析对不对,不知道怎么处理。
补上admin.py对应视图函数代码
@admin_bp.route('/post/new', methods=['GET', 'POST'])
#@login_required
def new_post():
form = PostForm()
if form.validate_on_submit():
title = form.title.data
body = form.body.data
category = Category.query.get(form.category.data)
post = Post(title=title, body=body, category=category)
# same with:
# category_id = form.category.data
# post = Post(title=title, body=body, category_id=category_id)
db.session.add(post)
db.session.commit()
flash('Post created.', 'success')
return redirect(url_for('blog.show_post', post_id=post.id))
return render_template('admin/new_post.html', form=form)