【问题标题】:Mongoengine, Flask and ReferenceField in WTFormsWTForms 中的 Mongoengine、Flask 和 ReferenceField
【发布时间】:2014-02-21 07:57:07
【问题描述】:

大家好, 我正在实现一个 Flask/MongoDB 项目,因为我是这个世界的新手,所以我遵循了这个页面上的教程: http://docs.mongodb.org/ecosystem/tutorial/write-a-tumblelog-application-with-flask-mongoengine/

之后,我开始编写自己的应用程序,这是代码的一部分:

型号:

class Generic(db.Document):
    descrizione = db.StringField(max_length=255, required=True)

    meta = {
        'allow_inheritance': True,
        'indexes': [
            {'fields': ['descrizione'], 'unique': True}
        ]
    }

class Category(Generic):
    def __call__(self, *args):
        pass

class User(db.Document):
    email = db.EmailField(max_length=255, required=True)
    nickname = db.StringField(max_length=255, required=True)
    password = db.StringField(max_length=16, required=True)
    categoria = db.ReferenceField('Category', required=True)

    meta = {
        'indexes': [
            {'fields': ['nickname', 'email'], 'unique': True}
        ]
    }

正如您在上面看到的,我有一个“类别”类,它继承了“通用”类。 “用户”类最终具有类别的参考字段。这样,当我创建用户时,mongo db 上的类别字段存储为 ObjectID,与包含我创建的所有类别的“通用”集合相关。

下一步是创建表单以将新文档插入到用户集合中。 在我的 Views python 文件中,我有这个:

def iscrizione():

    form = model_form(User, only=['email', 'nickname', 'password', 'categoria'])(request.form)

    if request.method == 'GET':
        ctx = {
            'form': form
        }
        return render_template('users/iscrizione.html', **ctx)

模板使用教程页面中报告的 Jinja 宏:

{% macro render(form) -%}
<fieldset>
{% for field in form %}
{% if field.type in ['CSRFTokenField', 'HiddenField'] %}
  {{ field() }}
{% else %}
  <div class="clearfix {% if field.errors %}error{% endif %}">
    {{ field.label }}
<div class="input">
  {% if field.name == "body" %}
    {{ field(rows=10, cols=40) }}
  {% else %}
    {{ field() }}
  {% endif %}
  {% if field.errors or field.help_text %}
    <span class="help-inline">
    {% if field.errors %}
      {{ field.errors|join(' ') }}
    {% else %}
      {{ field.help_text }}
    {% endif %}
    </span>
  {% endif %}
</div>
</div>
{% endif %}
{% endfor %}
</fieldset>
{% endmacro %}

最后,这是我的问题 (如果你达到了这个文字,你就是我的英雄)

当我使用呈现的表单访问网页时,宏会正确显示文本字段,并且对于我模型中的 ReferenceField,它会显示一个组合框。 选择组合中的选项值与我创建的类别文档的对象 ID 完全对齐。选择其中一个并提交表单,我的应用程序会正确创建新的用户文档。

不幸的是,选择框标签没有显示人类可读的值,报告“类别对象”。

<select id="categoria" name="categoria">
  <option value="530536363c74031c24ee7ab6">Category object</option>
  <option value="5305362d3c74031c24ee7ab5">Category object</option>
  <option value="530535793c74031b73dd07b4">Category object</option>
</select>

如何才能为选择框显示正确的标签?

【问题讨论】:

    标签: python wtforms flask-mongoengine


    【解决方案1】:

    也许它对某人有用。您可以使用标准方法,例如定义

    def __str__(self):
        return self.descrizione
    

    为您的类别类

    【讨论】:

      【解决方案2】:

      这也可以通过model_form函数中的字段args来实现:

      form = model_form(
          User,
          only=['email', 'nickname', 'password', 'categoria'],
          field_args={'categoria': {'label_attr': 'descrizione'}}
      )
      

      【讨论】:

        【解决方案3】:

        我终于成功了! 假设 User 文档的字段“categoria”是“Category”集合的 ReferenceField。 只需使用您想要作为标签的类别模型的字段名称将“label_attr”属性添加到“form.categoria”。

        def iscrizione():
            form = model_form(User, only=['email', 'nickname', 'password', 'categoria'])(request.form)
            form.categoria.label_attr='descrizione'  #<< add this line
            if request.method == 'GET':
                ctx = {
                'form': form
            }
            return render_template('users/iscrizione.html', **ctx)
        

        【讨论】:

          猜你喜欢
          • 2014-08-11
          • 2014-02-09
          • 1970-01-01
          • 2012-02-29
          • 1970-01-01
          • 1970-01-01
          • 2012-07-16
          • 2013-07-01
          • 1970-01-01
          相关资源
          最近更新 更多