【问题标题】:Can you have multiple instances of a WTForm?可以有多个 WTForm 实例吗?
【发布时间】:2014-10-30 17:17:01
【问题描述】:

我正在内部应用程序上实现一个评论系统(使用 Python/Flask/WTForms),它允许评论,以及每个子集下的单个级别。

Comments 可以很好地与一个简单的 WTForm 类一起使用,例如:

类 CommentForm(Form): comment = TextAreaField('Comment', validators=[DataRequired()])

然后将其调用到 Jinja2 模板中。

问题是如何实施“子”cmets。这是子评论和父评论之间基本的多对一外键关系。挑战在于给定屏幕上可以有多个评论,但只有一个评论表单。但是,每个评论都有关联的 Subcmets,因此 Subcomment 表单需要在屏幕上多次呈现(在每个评论下),我预计在呈现和提交表单时会发生冲突(在此处使用 WTForms)。

该模型与 Stackoverflow 非常相似,其中有一个问题 > 许多与问题相关的评论和 > 与每个评论相关的许多子评论。

简单地不对 Subcmets 使用 WTForms 并公开一个简单的 REST API 并旋转一点 AJAX 以将 Subcomment 提交到 REST 端点会更容易吗?

【问题讨论】:

    标签: python flask wtforms


    【解决方案1】:

    是的,仅在需要时创建表单比将 N+1 个表单(其中 N 是 cmets 的数量)发送给客户要简单得多 - 但是,如果您正在考虑采用渐进增强的方法那么这就是你需要做的。

    在这种情况下,您只需将数据转换为表单,并在服务器端处理响应:

    class CommentForm(Form):
        parent_id = IntegerField(widget=HiddenWidget)
        comment = TextAreaField("Comment", validators=[InputRequired()])
    
    # Then, in your view handler
    comments = get_comment_list()
    comments = [CommentForm(comment.id, comment.text) for comment in comments]
    return render_template(article=article, comments=comments)
    
    # And in your "comment" endpoint you simply handle the comment
    comment = CommentForm(request.post)
    
    # This shouldn't be necessary, but it's just an example of figuring out
    # what's going on from the data provided
    if comment.parent_id.data:
        # Insert into comment chain
    else:
        # It is a rootless comment
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-09
      • 1970-01-01
      • 2012-05-03
      • 2020-09-13
      • 2019-09-27
      • 1970-01-01
      • 1970-01-01
      • 2015-05-19
      相关资源
      最近更新 更多