Flask-WTF在编辑一个记录的时候,遇到下拉菜单如何自动跳到数据默认的选项上?
现在遇到一个问题就是编辑一个记录的时候,从数据库里读出来的数据在前台不能同步。QuerySelectField总是显示第一条记录.也就是说。并没有根据数据库的值自动同步选项。
Model: class Article(db.Model): id=db.Column(db.Integer,primary_key=True) node=db.Column(db.Integer,db.ForeignKey("node.id"), nullable=False, index=True, ) title=db.Column(db.Unicode(200)) content=db.Column(db.Text) created = db.Column(db.DateTime, default=datetime.now) _tags=db.Column(db.Unicode(200),index=True) hits = db.Column(db.Integer, default=1) class Node(db.Model): id=db.Column(db.Integer,primary_key=True) name=db.Column(db.String(200),nullable=False) slug = db.Column(db.String(200), nullable=False, index=True, unique=True) ============== Form的定义: class ArticleForm(Form): title=TextField("title") content=TextAreaField("content") node=QuerySelectField("node",query_factory=lambda :Node.query.all(),get_pk=lambda x:x.id,get_label=lambda x:x.name) tags = TextField("Tags") submit = SubmitField(u"提交") ============== view: def editarticle(article_id): art=Article.query.filter(Article.id==article_id).first_or_404() form=ArticleForm(obj=art) if form.validate_on_submit(): form.populate_obj(art) art.node=form.node.data.id db.session.add(art) db.session.commit() return redirect(url_for(".listarticle")) return render_template("/admin/create_article.html",form=form)
请问我应该如何做,才能在编辑一个ariticle的时候,Node这个字段的下拉菜单自动显示artilce数据库里的相应的情况?
It seems to be a front-end problem.
The solution can be to use ajax to request synchronized data from the server when pulling down, and then jquery to change the html, or it seems that you can also use something like angular.js. Anyway, I haven’t seen any solution purely by modifying the background. Method
In the drop-down menu, the value of <option> should be of character type, otherwise it will not be recognized. You can set the default value. You also need to specify it as character type when specifying form.field_name.data.