Django 2 升级后,filter_horizontal 功能丢失。

4
我最近升级到了Django 2.2.2和Python 3.6.8,我的Django管理页面中的filter_horizontal功能消失了。
我尝试在Chrome无痕模式下查看我的管理页面,一些答案建议这样做,我还尝试将verbose_name字符串更改为unicode。然而,这些方法都没有奏效。
这是一个模型的示例,我正在尝试显示其中的filter_horizontal。在升级之前,这在我的应用程序上可以正常工作。

admin.py

class ResearchAdmin(admin.ModelAdmin):
    filter_horizontal = ('criteria', 'state')
    
    def save_model(self, request, obj, form, change):
        obj.save()

        # Update cache for tasks containing the saved goal
        tasks = Task.objects.filter(research__id=obj.pk).values_list('pk', flat=True)
        for t in tasks:
            cache.delete_many(['task%s' % t, 'task%s_research' % t])

models.py

    """
        Clinical Research model
    """
    def __str__(self):
        return "%s" % (self.name)

    name = models.CharField(max_length=50, null=True, blank=True)
    type = models.CharField(max_length=50, null=True, blank=True)
    cta = models.CharField(max_length=50, null=True, blank=True)
    description = models.TextField(null=True, blank=True)
    picture = models.ImageField(upload_to='images/%Y/%m/%d', null=True, blank=True, help_text="Upload portrait image for modal study description")
    layout = models.CharField(max_length=1, choices=LAYOUT_TYPE, null=False, blank=False, default='r')
    criteria = models.ManyToManyField('Answer', blank=True, db_index=True, help_text="Answers required for qualified patients")
    required_contact = models.ManyToManyField('ContactField', blank=True, db_index=True, help_text="Contact info for patient to enter")
    email = models.EmailField(null=True, blank=True, help_text="Sponsor email for notifying of screened patients")
    link = models.URLField(null=True, blank=True)
    state = models.ManyToManyField('State', blank=True, help_text="Qualifying states")
    lat = models.CharField(max_length=60, null=True, blank=True)
    lng = models.CharField(max_length=60, null=True, blank=True)
    distance = models.PositiveIntegerField(null=True, blank=True, help_text="Maximum distance from user in miles to show")

    class Meta:
        verbose_name = u"Research"
        verbose_name_plural = u"Research"

没有错误信息,但是criteriastate字段的filter_horizontal前端在管理界面中没有显示出来。

##collectstatic## 正如@iain-shelvington所建议的那样,这个问题可能是由于与显示filter_horizontal格式所需的缓存前端代码的某种干扰导致的。我尝试在Google隐身模式下运行,清除缓存,并运行collectstatic --clear,但这些都没有起作用。此外,在升级前后的管理静态文件之间没有任何区别。

@SylvainBiehler指出django_gulp可能会覆盖collectstatic。我禁用了django_gulp并运行了./manage.py collectstatic --clear,所有管理文件现在在Django升级后都已更新。

##比较Django升级前后的管理文件## 我能够启动一个Django升级前的版本的应用程序,旧版本中的filter_horizontal功能是有效的。从Chrome控制台中Criteria字段的构造中存在一些差异:

旧版本(有效)

选择选项之前的元素:
<select multiple="multiple" class="selectfilter" id="id_criteria" name="criteria">

选择后的Javascript:

<script type="text/javascript">addEvent(window, "load", function(e) {SelectFilter.init("id_criteria", "criteria", 0, "https://xxxxxxx/static/admin/"); });</script>

新版本(已损坏)

选择元素稍有不同。在选项后没有javascript:

<select name="criteria" id="id_criteria" multiple class="selectfilter" data-field-name="criteria" data-is-stacked="0">

这似乎是导致问题的原因,但我不知道如何解决。有什么想法吗?
##在控制台中分析管理员JS## SelectBox.js在控制台中加载并声明var = SelectBox = {...,但从未被调用。 SelectFilter.js也加载了,但该函数从未被调用:
/*
SelectFilter2 - Turns a multiple-select box into a filter interface.

Requires core.js, SelectBox.js and addevent.js.
*/
(function($) {
function findForm(node) {
    // returns the node of the form containing the given node
    if (node.tagName.toLowerCase() != 'form') {
        return findForm(node.parentNode);
    }
    return node;
}

window.SelectFilter = {
    init: function(field_id, field_name, is_stacked, admin_static_prefix) {
        if (field_id.match(/__prefix__/)){
            // Don't intialize on empty forms.
            return;
        }
        var from_box = document.getElementById(field_id);
        from_box.id += '_from'; // change its ID
        from_box.className = 'filtered';

        var ps = from_box.parentNode.getElementsByTagName('p');
        for (var i=0; i<ps.length; i++) {
            if (ps[i].className.indexOf("info") != -1) {
                // Remove <p class="info">, because it just gets in the way.
                from_box.parentNode.removeChild(ps[i]);
            } else if (ps[i].className.indexOf("help") != -1) {
                // Move help text up to the top so it isn't below the select
                // boxes or wrapped off on the side to the right of the add
                // button:
                from_box.parentNode.insertBefore(ps[i], from_box.parentNode.firstChild);
            }
        }

        // <div class="selector"> or <div class="selector stacked">
        var selector_div = quickElement('div', from_box.parentNode);
        selector_div.className = is_stacked ? 'selector stacked' : 'selector';

        // <div class="selector-available">
        var selector_available = quickElement('div', selector_div, '');
        selector_available.className = 'selector-available';
        var title_available = quickElement('h2', selector_available, interpolate(gettext('Available %s') + ' ', [field_name]));
        quickElement('img', title_available, '', 'src', admin_static_prefix + 'img/icon-unknown.gif', 'width', '10', 'height', '10', 'class', 'help help-tooltip', 'title', interpolate(gettext('This is the list of available %s. You may choose some by selecting them in the box below and then clicking the "Choose" arrow between the two boxes.'), [field_name]));

        var filter_p = quickElement('p', selector_available, '', 'id', field_id + '_filter');
        filter_p.className = 'selector-filter';

        var search_filter_label = quickElement('label', filter_p, '', 'for', field_id + "_input");

        var search_selector_img = quickElement('img', search_filter_label, '', 'src', admin_static_prefix + 'img/selector-search.gif', 'class', 'help-tooltip', 'alt', '', 'title', interpolate(gettext("Type into this box to filter down the list of available %s."), [field_name]));

        filter_p.appendChild(document.createTextNode(' '));

        var filter_input = quickElement('input', filter_p, '', 'type', 'text', 'placeholder', gettext("Filter"));
        filter_input.id = field_id + '_input';

        selector_available.appendChild(from_box);
        var choose_all = quickElement('a', selector_available, gettext('Choose all'), 'title', interpolate(gettext('Click to choose all %s at once.'), [field_name]), 'href', 'javascript: (function(){ SelectBox.move_all("' + field_id + '_from", "' + field_id + '_to"); SelectFilter.refresh_icons("' + field_id + '");})()', 'id', field_id + '_add_all_link');
        choose_all.className = 'selector-chooseall';

        // <ul class="selector-chooser">
        var selector_chooser = quickElement('ul', selector_div, '');
        selector_chooser.className = 'selector-chooser';
        var add_link = quickElement('a', quickElement('li', selector_chooser, ''), gettext('Choose'), 'title', gettext('Choose'), 'href', 'javascript: (function(){ SelectBox.move("' + field_id + '_from","' + field_id + '_to"); SelectFilter.refresh_icons("' + field_id + '");})()', 'id', field_id + '_add_link');
        add_link.className = 'selector-add';
        var remove_link = quickElement('a', quickElement('li', selector_chooser, ''), gettext('Remove'), 'title', gettext('Remove'), 'href', 'javascript: (function(){ SelectBox.move("' + field_id + '_to","' + field_id + '_from"); SelectFilter.refresh_icons("' + field_id + '");})()', 'id', field_id + '_remove_link');
        remove_link.className = 'selector-remove';

        // <div class="selector-chosen">
        var selector_chosen = quickElement('div', selector_div, '');
        selector_chosen.className = 'selector-chosen';
        var title_chosen = quickElement('h2', selector_chosen, interpolate(gettext('Chosen %s') + ' ', [field_name]));
        quickElement('img', title_chosen, '', 'src', admin_static_prefix + 'img/icon-unknown.gif', 'width', '10', 'height', '10', 'class', 'help help-tooltip', 'title', interpolate(gettext('This is the list of chosen %s. You may remove some by selecting them in the box below and then clicking the "Remove" arrow between the two boxes.'), [field_name]));

        var to_box = quickElement('select', selector_chosen, '', 'id', field_id + '_to', 'multiple', 'multiple', 'size', from_box.size, 'name', from_box.getAttribute('name'));
        to_box.className = 'filtered';
        var clear_all = quickElement('a', selector_chosen, gettext('Remove all'), 'title', interpolate(gettext('Click to remove all chosen %s at once.'), [field_name]), 'href', 'javascript: (function() { SelectBox.move_all("' + field_id + '_to", "' + field_id + '_from"); SelectFilter.refresh_icons("' + field_id + '");})()', 'id', field_id + '_remove_all_link');
        clear_all.className = 'selector-clearall';

        from_box.setAttribute('name', from_box.getAttribute('name') + '_old');

        // Set up the JavaScript event handlers for the select box filter interface
        addEvent(filter_input, 'keyup', function(e) { SelectFilter.filter_key_up(e, field_id); });
        addEvent(filter_input, 'keydown', function(e) { SelectFilter.filter_key_down(e, field_id); });
        addEvent(from_box, 'change', function(e) { SelectFilter.refresh_icons(field_id) });
        addEvent(to_box, 'change', function(e) { SelectFilter.refresh_icons(field_id) });
        addEvent(from_box, 'dblclick', function() { SelectBox.move(field_id + '_from', field_id + '_to'); SelectFilter.refresh_icons(field_id); });
        addEvent(to_box, 'dblclick', function() { SelectBox.move(field_id + '_to', field_id + '_from'); SelectFilter.refresh_icons(field_id); });
        addEvent(findForm(from_box), 'submit', function() { SelectBox.select_all(field_id + '_to'); });
        SelectBox.init(field_id + '_from');
        SelectBox.init(field_id + '_to');
        // Move selected from_box options to to_box
        SelectBox.move(field_id + '_from', field_id + '_to');

        if (!is_stacked) {
            // In horizontal mode, give the same height to the two boxes.
            var j_from_box = $(from_box);
            var j_to_box = $(to_box);
            var resize_filters = function() { j_to_box.height($(filter_p).outerHeight() + j_from_box.outerHeight()); }
            if (j_from_box.outerHeight() > 0) {
                resize_filters(); // This fieldset is already open. Resize now.
            } else {
                // This fieldset is probably collapsed. Wait for its 'show' event.
                j_to_box.closest('fieldset').one('show.fieldset', resize_filters);
            }
        }

        // Initial icon refresh
        SelectFilter.refresh_icons(field_id);
    },
    refresh_icons: function(field_id) {
        var from = $('#' + field_id + '_from');
        var to = $('#' + field_id + '_to');
        var is_from_selected = from.find('option:selected').length > 0;
        var is_to_selected = to.find('option:selected').length > 0;
        // Active if at least one item is selected
        $('#' + field_id + '_add_link').toggleClass('active', is_from_selected);
        $('#' + field_id + '_remove_link').toggleClass('active', is_to_selected);
        // Active if the corresponding box isn't empty
        $('#' + field_id + '_add_all_link').toggleClass('active', from.find('option').length > 0);
        $('#' + field_id + '_remove_all_link').toggleClass('active', to.find('option').length > 0);
    },
    filter_key_up: function(event, field_id) {
        var from = document.getElementById(field_id + '_from');
        // don't submit form if user pressed Enter
        if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) {
            from.selectedIndex = 0;
            SelectBox.move(field_id + '_from', field_id + '_to');
            from.selectedIndex = 0;
            return false;
        }
        var temp = from.selectedIndex;
        SelectBox.filter(field_id + '_from', document.getElementById(field_id + '_input').value);
        from.selectedIndex = temp;
        return true;
    },
    filter_key_down: function(event, field_id) {
        var from = document.getElementById(field_id + '_from');
        // right arrow -- move across
        if ((event.which && event.which == 39) || (event.keyCode && event.keyCode == 39)) {
            var old_index = from.selectedIndex;
            SelectBox.move(field_id + '_from', field_id + '_to');
            from.selectedIndex = (old_index == from.length) ? from.length - 1 : old_index;
            return false;
        }
        // down arrow -- wrap around
        if ((event.which && event.which == 40) || (event.keyCode && event.keyCode == 40)) {
            from.selectedIndex = (from.length == from.selectedIndex + 1) ? 0 : from.selectedIndex + 1;
        }
        // up arrow -- wrap around
        if ((event.which && event.which == 38) || (event.keyCode && event.keyCode == 38)) {
            from.selectedIndex = (from.selectedIndex == 0) ? from.length - 1 : from.selectedIndex - 1;
        }
        return true;
    }
}

})(django.jQuery);

##已安装应用##

########## APP CONFIGURATION

INSTALLED_APPS = DJANGO_APPS + LOCAL_APPS

DJANGO_APPS = (
    'django_gulp',
    # Default Django apps:
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # Useful template tags:
    # 'django.contrib.humanize',

    # Python-Social-Auth
    'social_django',

    # Admin panel and documentation:
    'django.contrib.admin',
    'django.core.management',
    # 'django.contrib.admindocs',

    # for task queue

    # For django-storages static store on AWS S3
    'storages',

    # Other django apps
    'rest_framework',
)

# Apps specific for this project go here.
LOCAL_APPS = (
    'base',
    'myproject',
    'users',
    'campaigns',
)

1
你尝试过运行collectstatic并清除浏览器缓存吗? - Iain Shelvington
3
请问您能否在控制台中验证 SelectBox.jsSelectFilter2.js 是否已加载?这两个文件用于显示水平小部件。 - Sylvain Biehler
1
有趣的是 SelectFilter2.js 的末尾包含一个触发器,当你的类为 selectfilter 的选择加载完成时应该被调用。 - Sylvain Biehler
2
由于 django_gulp 覆盖了 collectstaticrunserver,你能否在不使用 django_gulp 的情况下重试 collectstatic --clear - Sylvain Biehler
1
@SylvainBiehler 我认为你是对的,问题与 collectstatic 有关,因为我的管理静态文件(存储在 S3 上)最后修改是几个月前,尽管今天运行了 collectstatic --clear(带或不带 django_gulp)。当我运行 collectstatic --clear --verbosity 2 时,它显示正在跳过未修改的文件,而不是删除它们。仍在研究如何解决这个问题。 - wraasch
显示剩余12条评论
1个回答

0

我使用终端中的以下命令从Django.contrib复制了静态/管理文件:

cp -a /Users/username/.virtualenvs/rs/lib/python3.9/site-packages/django/contrib/admin/. /Users/username/Documents/myproject/static/

然后我运行了collectstatic将文件上传到S3,在那里它们被存储用于生产。这实际上是有效的,但似乎有点hacky。我一定没有做对某些事情,以至于这些文件在Django升级时没有更新。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接