大家好,我正在实现一个 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>
如何设法为选择框显示正确的标签?