如何将查询结果发送到WTForm字段?
作者:互联网
我使用带有多对多表的SQLalchemy来管理博客帖子标签.我需要帮助将标记值呈现到TextArea表单字段中,以便对其进行编辑.现在,当我渲染时,我看到了查询查询.
模型
Tag和Post之间的关系在`tags’中定义
class Tag(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), unique=True)
url = db.Column(db.String(120), unique=True)
def __init__(self, name, url):
self.name = name
self.url = url
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(80))
body = db.Column(db.Text)
pub_date = db.Column(db.DateTime)
tags = db.relationship('Tag', secondary=posts_tags, backref='posts', lazy='dynamic')
class Tag(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), unique=True)
url = db.Column(db.String(120), unique=True)
我的问题是在WTF中渲染标签字段.我在字段中显示查询而不是结果.
我看到两种方法可以修复,但我不知道该怎么办….
a.)在视图中,通过标签进行交互并显示值.
b.)在自定义字段中,以某种方式传递post id并在rend字段之前运行查询.像这样……
Field Hack可行,但知道如何动态地将Post ID传递给该字段.*
class TagListField(Field):
widget = TextArea()
def _value(self):
q = Post.query.join(posts_tags, (posts_tags.c.post_id == {{ NEED HELP HERE}}))
taglist = []
for p in q:
for t in p.tags:
taglist.append(t.name)
taglist
return ", ".join(taglist)
def process_formdata(self, valuelist):
if valuelist:
self.data = [x.strip() for x in valuelist[0].split(',')]
else:
self.data = []
希望看到视图和字段选项……谢谢并提前…
解决方法:
您正在错误地使用_value,它用于显示数据,而不是用于设置数据.
数据在表单上设置,而不是在字段上设置.
class TagListField(Field):
widget = TextInput()
def _value(self):
if self.data:
return u', '.join(self.data)
else:
return u''
def process_formdata(self, valuelist):
if valuelist:
self.data = [x.strip() for x in valuelist[0].split(',')]
else:
self.data = []
class PostForm(Form):
title = StringField(u'title', validators=[DataRequired()])
body = StringField(u'Text', widget=TextArea())
pub_date = DateTimeField(u'date create')
topic = QuerySelectField(query_factory=enabled_topics, allow_blank=True)
tags = TagListField(u'Tags') # here you use your custom field
# a method to set the tags
def fill_tags(self, tags):
self.tags.data = tags
# and from the view that is creating the form you send the list of tags
在你看来:
form = PostForm()
form.fill_tags([tag.name for tag in post.tags.all()])
标签:flask-wtforms,wtforms,python,sqlalchemy,flask 来源: https://codeday.me/bug/20191003/1846722.html