Django:AJAX ManyToManyField in admin [英] Django: AJAX ManyToManyField in admin

查看:380
本文介绍了Django:AJAX ManyToManyField in admin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在管理中显示 ManyToManyField ,就像 filter_horizo​​ntal 一样,但填充用户类型的选项进入过滤器字段。有很多选项,一次加载它们需要很多时间。

I want to display ManyToManyFields in admin just like filter_horizontal does, but populate the options as the user types into the filter field. There are many options and loading them all at once takes a lot of time.

我发现 django -axax过滤字段,但是对我来说似乎是一个过分的,因为它需要更改模型类,所有我想要做的是替换表单中的每个多个选择字段。

I found django-ajax-filtered-fields but it seems to me an overkill as it requires changes to model classes, when all I want to do is to replace every multiple select field in a form.

编写从 admin.widgets.FilteredSelectMultiple 继承的自定义窗口小部件字段似乎是正确的方法。所以我试图滚动自己的小部件:

Writing a custom widget field that inherits from admin.widgets.FilteredSelectMultiple seems to be the right way. So I am trying to roll my own widget:

class MultiSelectWidget(FilteredSelectMultiple):
    class Media:
        # here should be some js to load options dynamically
        js = (
            "some_js_to_load_ajax_options.js",
        )

    def render_options(self, choices, selected_choices):
        # this initializes the multiple select without any options
        choices = [c for c in self.choices if str(c[0]) in selected_choices]
        self.choices = choices
        return super(MultiSelectWidget, 
                     self).render_options([], selected_choices)

class MyAdminForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(MyAdminForm, self).__init__(*args, **kwargs)
        self.fields['m2m_field'].widget = MultiSelectWidget('m2m_field', is_stacked=False)
    class Meta:
        model = MyModel

class MyAdmin(admin.ModelAdmin):
    form = MyAdminForm

正确呈现。

但我不知道如何实现这个 some_js_to_load_ajax_options.js ajax部分。我应该写我自己的jQuery片段,或修改 admin / media / js 附带的 SelectFilter2 ?任何人以前都在那里?

But I am not sure how to implement this some_js_to_load_ajax_options.js ajax part. Should I write my own jQuery snippet or modify SelectFilter2 which comes with admin/media/js? Anybody been there before?

编辑:
虽然与问题的核心无关,因为我只想覆盖字段的小部件,较短的方法是使用 formfield_overrides

class MultiSelectWidget(FilteredSelectMultiple):
    # as above

class MyAdmin(admin.ModelAdmin):
    formfield_overrides = {
        models.ManyToManyField: {'widget': MultiSelectWidget},
    }


推荐答案

我从你的代码开始,我使用自定义JavaScript从photologue照片模型检索值;请注意,我正在使用grappelli,并且获取json对象的Django url是硬编码的;我的模型中的字段也被称为照片:

I started from your code and I used a custom javascript to retrieve values from photologue Photo model; please note that I'm using grappelli and the Django url that get the json object is hardcoded; also the field in my model is called "photos":

# urls.py
url(r'^get_json_photos/(?P<query>[\w-]+)/$', 'catalogo.views.get_json_photos', name='get_json_photos'),


# views.py    
from photologue.models import Photo
from django.utils import simplejson as json

def get_json_photos(request, query):
    photos = Photo.objects.filter(title__icontains=query)[:20]
    p = [ {"name":photo.title, "id":photo.id} for photo in photos ]
    response = json.dumps(p)
    return HttpResponse(response, mimetype="application/json")


# admin.py
from django.conf import settings
from django.contrib.admin.widgets import FilteredSelectMultiple

class MyFilteredSelectMultiple(FilteredSelectMultiple):

    class Media:
        js = (settings.ADMIN_MEDIA_PREFIX + "js/core.js",
              settings.ADMIN_MEDIA_PREFIX + "js/SelectBox.js",
              settings.ADMIN_MEDIA_PREFIX + "js/SelectFilter2.js",
              settings.MEDIA_URL + "js/ajax_photo_list.js")


class MyModelMultipleChoiceField(ModelMultipleChoiceField):

    def clean(self, value):
        return [val for val in value]


class GalleryForm(forms.ModelForm):
    photos = MyModelMultipleChoiceField(queryset=Photo.objects.none(), required=False,
        widget=MyFilteredSelectMultiple(verbose_name="photos", is_stacked=False))

    def __init__(self, *args, **kwargs):
        super(GalleryForm, self).__init__(*args, **kwargs)
        try:
            i = kwargs["instance"]
            gallery = Gallery.objects.get(pk=i.pk)
            qs = gallery.photos.all()
        except:
            qs = Photo.objects.none()
        self.fields['photos'].queryset = qs

    class Meta:
        model = Gallery
        widgets = {
            'photos': MyFilteredSelectMultiple(verbose_name="photos", is_stacked=False)
        }


class GalleryAdmin(admin.ModelAdmin):
    list_display = ('title', 'date_added', 'photo_count', 'is_public')
    list_filter = ['date_added', 'is_public']
    date_hierarchy = 'date_added'
    prepopulated_fields = {'title_slug': ('title',)}
    filter_horizontal = ()
    form = GalleryForm


# ajax_photo_list.js 
(function($){
$("#id_photos_input").live("keyup", function(){
    var querystring = $("#id_photos_input").val();
    if (querystring) {
        $.ajax ({
            type: "GET",
            url: "/get_json_photos/"+querystring+"/",
            cache: false,
            success: function(json) {
                if (json) {
                    var list_from = $("#id_photos_from option").map(function() {
                        return parseInt($(this).val());
                    });
                    var list_to = $("#id_photos_to option").map(function() {
                        return parseInt($(this).val());
                    });
                    for (var pid in json) {
                        if ($.inArray(json[pid].id, list_from) == -1 && $.inArray(json[pid].id, list_to) == -1) {
                            $("#id_photos_from").prepend("<option value='"+json[pid].id+"'>"+json[pid].name+"</option>");
                        }
                    }
                    SelectBox.init('id_photos_from');
                    SelectBox.init('id_photos_to');
                }
            }
        });
    }
})
}(django.jQuery));

我在想让它通用,因为我不是第一次有这个问题,

I'm thinking to make it generic, since is not the first time that I have this problem,

这篇关于Django:AJAX ManyToManyField in admin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆