在raw_id_fields中一次插入更多记录

时间:2013-02-04 11:56:17

标签: django django-admin

我有一个m2m关系,在我的AdminForm中,我会使用raw_id_fields而不是filter_horizo​​ntal选项。为了解释,我更喜欢raw_id_fields而不是filter_horizo​​ntal选项,因为记录已经被分类了。因此,在弹出窗口中,用户可以通过类别进行搜索和过滤。 但有两点我无法弄清楚:

  • 可以在弹出窗口中选择多个记录
  • 在input_field
  • 中显示真实姓名而不是pk

2 个答案:

答案 0 :(得分:0)

  1. 这是可能的。要选择多条记录,您需要在dismissRelatedLookupPopup()中覆盖默认django/contrib/admin/static/admin/js/admin/RelatedObjectLookups.js,方法是将您的脚本包含在Media或小部件的ModelAdmin类中:

    var dismissRelatedLookupPopup = (function(prev, $) {
        return function(win, chosenId) {
            var name = windowname_to_id(win.name);
            var elem = document.getElementById(name);
    
            // 1. you could add extra condition checking here, for example
            if ($(elem).hasClass('my_raw_id_ext_cls')) { // add this class to the field
            //     ...logic of inserting picked items from the popup page
            } 
            else { // default logic
                prev(win, chosenId);
            }
    
            // 2. or you could copy the following part from RelatedObjectLookups.js ...
            if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) {    
                elem.value += ',' + chosenId;
                // 2. and add a return. Remember this acts globally.
                return;
            } else {
                document.getElementById(name).value = chosenId;
            }
    
            // 3. the following line cause the popup to be closed while one item is picked. 
            // You could comment it out, but this would also affect the behavior of picking FK items.
            win.close(); 
    
        }
    })(dismissRelatedLookupPopup, django.jQuery);
    
  2. Django默认不支持此功能。 djangosnippets.org有一些片段,您可能需要查看它们。

答案 1 :(得分:0)

最后我使用了修改后的https://django-salmonella.readthedocs.org/en/latest/。我没有显示输入字段并在表格中显示所选记录。