我想在管理员中显示ManyToManyField
,就像filter_horizontal
一样,但是在用户输入过滤器字段时填充选项。有很多选项,一次加载它们需要花费很多时间。
我发现django-ajax-filtered-fields但在我看来它是一种矫枉过正,因为它需要更改模型类,当我想要做的就是替换表单中的每个多个选择字段时。
编写一个继承自admin.widgets.FilteredSelectMultiple
的自定义窗口小部件字段似乎是正确的方法。所以我试图推出自己的小部件:
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代码段还是修改SelectFilter2
附带的admin/media/js
?以前有人去过吗?
修改
虽然与问题的核心无关,但由于我只想覆盖字段的小部件,因此更短的方法是使用formfield_overrides
:
class MultiSelectWidget(FilteredSelectMultiple):
# as above
class MyAdmin(admin.ModelAdmin):
formfield_overrides = {
models.ManyToManyField: {'widget': MultiSelectWidget},
}
答案 0 :(得分:4)
我从你的代码开始,我使用自定义javascript从photologue Photo模型中检索值;请注意我正在使用grappelli和Django url来获取json对象是硬编码的;我模型中的字段也称为“照片”:
# 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));
我正在考虑让它变得通用,因为这不是我第一次遇到这个问题,
答案 1 :(得分:0)
我会破解选择过滤器,它有一组很好的功能可以使用。
答案 2 :(得分:0)
如果Select2的用户界面吸引您,您可以在管理员中使用Django-Select2。
对于m2m,它可能会像你建议的那样工作:
class MyAdmin(admin.ModelAdmin):
formfield_overrides = {
models.ManyToManyField: {'widget': ModelSelect2MultipleWidget},
}
# required to make jquery available to select2
# has to be loaded via Admin class (and not via widget or form class) for correct order in output
class Media:
js = ("ext/js/jquery.min.js",)
Ajax的工作原理是将以下网址格式添加到urls.py
:
# if using ModelWidget
url(r'^select2/', include('django_select2.urls')),
当然,您也可以提供自己的视图实现,请参阅上面链接的文档。
我目前没有将它用于m2m,而是用于反向外键关系,因此我在Django管理员中以自定义形式使用它,明确地实例化窗口小部件。因此,如果它不与formfield_overrides
合作,那么漫长的选择将是一种选择。