首页 > 解决方案 > 使用 django-ajax-select 时,“+add”按钮无法正常工作

问题描述

简而言之:django-ajax-selects 可以很好地过滤现有项目,但通过添加新项目会产生 JS 错误。

细节。使用 Django 3.1。在管理站点,需要使用 ForeignField 创建模型 Choice 的对象来对 Question 建模。Django-ajax-selects ( DAS ) 用于填充字段(动态过滤)。通过输入字母,DAS 处理查询集并输出相关问题的列表。可以从列表中选择一个问题并保存新的选择。这一切都很好。

如果通过键入没有找到正确的问题,则可以单击+添加按钮并在带有表单的弹出窗口中添加新问题。根据 DAS 文档单击“保存”后:

  1. 新问题必须保存到数据库中;
  2. 弹出窗口必须关闭;
  3. 编辑的字段必须填充新问题。

带有弹出窗口的屏幕截图

问题是 Django 在第 2 步停止:创建了新问题,弹出窗口变得空白,并且没有以“弹出关闭...”在头部关闭。窗口出现JS错误:

    Uncaught TypeError: window.windowname_to_id is not a function
    at window.dismissAddRelatedObjectPopup (:8000/static/ajax_select/js/ajax_select.js:194)
    at popup_response.js:13

空白页的 HTML 代码是

<!DOCTYPE html>
<html>
  <head><title>Popup closing…&lt;/title></head>
  <body>
    <script id="django-admin-popup-response-constants"
            src="/static/admin/js/popup_response.js"
            data-popup-response="{&quot;value&quot;: &quot;6&quot;, &quot;obj&quot;: &quot;Question object (6)&quot;}">
    </script>
  </body>
</html>

这是来自 ajax_select.js 的一段 JS 代码,其中可能出现错误:

/* Called by the popup create object when it closes.
   * For the popup this is opener.dismissAddRelatedObjectPopup
   * Django implements this in RelatedObjectLookups.js
   * In django >= 1.10 we can rely on input.trigger('change')
   * and avoid this hijacking.
   */

  var djangoDismissAddRelatedObjectPopup = window.dismissAddRelatedObjectPopup || window.dismissAddAnotherPopup;
  window.dismissAddRelatedObjectPopup = function(win, newId, newRepr) {
    // Iff this is an ajax-select input then close the window and
    // trigger didAddPopup
    var name = window.windowname_to_id(win.name);

我在 Django 目录中的任何地方都找不到函数 windowname_to_id(),但是在 djangoprojects.com 的 10 年旧中,该函数是为 RelatedObjectLookups.js 提出的:

var uniqueness=(new Date()).valueOf();

function id_to_windowname(text) {
    text = text.replace(/\./g, '__dot__');
    text = text.replace(/\-/g, '__dash__');
    return uniqueness + text;
}

function windowname_to_id(text) {
    text = text.replace(uniqueness, '');
    text = text.replace(/__dot__/g, '.');
    text = text.replace(/__dash__/g, '-');
    return text;
}


我试图将这些函数几乎没有放入 ajax_select.js,但它没有帮助。如果没有 DAS,+add 按钮可以正常工作。

有什么想法可以解决这个问题吗?或者可能有人有一个带有添加功能的 django-ajax-selects 的工作示例?

标签: javascriptdjangodjango-ajax-selects

解决方案


该问题已由 DAS 开发人员解决,详情请参阅问题


推荐阅读