2010-11-19 52 views

回答

0

這看起來像只用JavaScript就能實現的那種東西。要將您自己的JavaScript添加到Django管理員,請參閱ModelAdmin media definitions的文檔。

0

這就是我想出來的。它完成了大部分工作。但是,添加新項目並且更改項目不會重定向回原始頁面時,列表不會更新。

/your_app/forms.py

class ProductForm(forms.ModelForm): 
    class Media: 
     js = ('js/custom_m2m.js',) 

    class Meta: 
     model = Product 

/your_media/js/custom_m2m.js

django.jQuery(function() { 
    var $ = django.jQuery; 

    // Add a new place holder div to hold the m2m list 
    $('div.options div').append('<div class="newdiv"></div>'); 

    // Assign some variables 
    var target = "options"; // <-- Target Field 
    var newdiv = $('div.newdiv'); 
    var next_page = window.location.pathname; 
    var add_link = $('div.'+target+' div a#add_id_'+target); 
    var edit_img = "/static/media_admin/img/admin/icon_changelink.gif"; 
    var add_img = "/static/media_admin/img/admin/icon_addlink.gif"; 

    // Make the placeholder div bit nicer 
    newdiv.attr("style", "line-height:20px; margin-left:105px;"); 

    // Iterate through select options and append them to 'newdiv' 
    $('select#id_'+target+' option[selected="selected"]').each(function() { 
     newdiv.append('<a href="/admin/shop/option/'+$(this).val()+'/?next='+next_page+'">'+$(this).text()+' <img src="'+edit_img+'" /></a><br />'); 
    }); 

    // Add a 'Add new' link after the option list 
    add_link.html('<strong>Add new</strong> ' + add_link.html()); 
    add_link.appendTo(newdiv); 

    // Show the 'newdiv' and hide the original dropdown 
    $('select#id_'+target).after(newdiv); 
    $('select#id_'+target).css("display", "none"); 
    $('div.'+target+' p[class="help"]').css("display", "none"); 
}); 

正如你所看到的,上面的腳本使用一些硬編碼路徑。任何改進都會有所幫助。