将空选项插入QuerySetSelectField

时间:2013-10-31 11:25:01

标签: python flask jquery-select2 mongoengine

我有一个类似

的模型
class AppMetaForm(BaseForm):
    category = QuerySetSelectField('CATEGORY'), queryset=AppCategory.objects())
    .....

在UI上,我使用select2使选择框更好。现在我想在每个选择框中添加像'-select-'这样的占位符。 Select2支持占位符,但在这种情况下它需要第一个空选项。所以我需要在类别选择列表中插入一个空记录。不幸的是,类别没有choices成员(因为它不是SelectField)。另外,我不能在字段定义中将参数allow_blankplaceholder一起使用,因为它不接受空白记录。

如果我将QuerySetSelectField替换为SelectField并通过查询填充它,将coerce设置为ObjectId,它正在运行但我无法插入空值,因为它正在发送服务器并导致错误“无不是ObjectId”。

如何实现理想的行为?

1 个答案:

答案 0 :(得分:0)

发现快速修复。我仍然不知道服务器端的更新选择,我主要是在客户端上做的。服务器端的一个注释 - 在模板中添加属性到字段data-placeholder="-select-"


$('select[data-placeholder]').each(function() {

    //Check whether any option is `selected`, pseudoattribute `:selected` here is unacceptable
    var selected = $('option[selected]', this);
    if (!selected.length) {

        //Creating fake option with valid but fake ObjectId and select it. 
        //If form returned after validation it already has `selected` option and I will not add placeholder to select.
        var option = $('<option>', {
            html: $(this).attr('data-placeholder'),
            selected: 'selected',
            value: '000000000000000000000000'
        });

        //Add this option first
        $(this).prepend(option);
    }
});

//Initialise all select tags with `select2` widget
$('select', container).select2({
    minimumResultsForSearch: -1,
    width: 'element'
});