如何在django中动态初始化FilteredSelectMultiple

时间:2015-03-05 13:52:06

标签: jquery django django-forms django-admin

我正在尝试在具有动态formset的自定义非管理网站上使用FilteredSelectMultiple小部件。我已经通过包含:

让窗口小部件中的现有条目正确显示
<script type="text/javascript" src="/static/admin/js/jquery.min.js"></script>
<script type="text/javascript" src="/static/admin/js/jquery.init.js"></script>
<script type="text/javascript" src="/admin/jsi18n"></script>

但是,当我在我的formset中添加另一个条目时(我尝试使用this plugin并通过使用ajax调用表单工厂视图),小部件显示为正常选择小部件,就像初始化脚本一样没有跑。

如何在运行中正确初始化FilteredSelectMultiple小部件的其他实例?

1 个答案:

答案 0 :(得分:2)

窗口小部件的编写方式仅在页面加载时初始化它,因此您添加的其他窗口小部件不会被初始化。处理这个问题的方法是链接到django动态formets生成的“添加”事件。我认为以下代码只有在您拥有这些小部件中的一个时才会起作用 - 如果每个'行'有多个小部件,则可能必须编写一个循环来迭代小部件。对不起,它不是世界上最干净的代码,但它适用于我的目的:

function enableHorizFilter(row){
    /* Row contains the whole row, select only our input box.
     * This could break if there are multiple widgets like this, I think. */
    filterbox = $(".selectfilter", row);
    //Selectfilter needs the ID
    filterboxID = filterbox.attr("id");
    /* Copied params from the source of the page, might break things if
     * I change the defaults, hardcoded */
    SelectFilter.init(filterboxID, "DATACLASSHERE", 0, "/static/admin/");
}

//this adds the formset controls
$('#YOURFORMIDHERE').formset({
  //every time something is added, do the following
  added: function(row){
    enableHorizFilter(row);
  }
});

相关问题