How to send query results to a WTForm Field?

做~自己de王妃 提交于 2019-11-29 17:46:38

You are using _value incorrectly, it's used to display the data, not to set the data.

The data is set on the Form, not on the Field.

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

in your view:

form = PostForm()
form.fill_tags([tag.name for tag in post.tags.all()])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!