3

I have a model in django admin as follows

ChoiceA= (
      ("on-false","on-false"),
       ("on-true","on-true"),
     )

ChoiceB =  (
        ("always","always"),
        ("never","never"),
       )
   id = models.CharField(verbose_name="Field",max_length=32)
   type = models.CharField(verbose_name="Expression",max_length=32)
   action = models.CharField(max_length=32, choices=x)

Now based on the type entered by the user ie if user enters type = "a" then action's choices should be set to ChoiceA and if user enters type ="b" then action's choices should be set to ChoiceB. How can I achieve this in Django Admin?

Edit:

action_change.js

jQuery(document).ready(function(){
$("#id_type").change( function(event) {
$.ajax({
        "type"     : "POST",
        "url"      : "/action_choices/",
        "dataType" : "json",
        "cache"    : false,
        "error"   :  alert("hello"),  
        "success"  : function(json) {
            $('#id_action >option').remove();
            for(var j = 0; j < json.length; j++){
                $('#id_action').append($('<option></option>').val(json[j][0]).html(json[j][1]));
            }
        }

});
});
});
4

2 に答える 2

6

あなたはAjaxとjQueryを使ってそれを達成することができます:

models.py:

type   = models.CharField(verbose_name="Expression",max_length=32)
action = models.CharField(max_length=32, choices = (('', ''), ))

admin.py:

class MyModelAdmin(admin.ModelAdmin):
    list_display = ('type', )

    class Media:
        js = ['/static/js/action_change.js']

admin.site.register(MyModel, MyModelAdmin)

urls.py:

url(r'^action_choices/', 'myproject.myapp.views.action_choices'),

views.py:

def action_choices(request): 
    action_list = []
    ChoiceA = ("on-false", "on-true")
    ChoiceB = ("always", "never")

    action_type = request.GET.get('action_type')
    if str(action_type).lower() == 'a':
        choices = ChoiceA
    elif str(action_type).lower() == 'b':
        choices = ChoiceB
    else:
        choices = ()

    [action_list.append((each,each)) for each in choices]
    json = simplejson.dumps(action_list)
    return HttpResponse(json, mimetype='application/javascript')

action_change.js静的フォルダに次のコンテンツを含むファイルを作成し、の正しいパスclass Mediaを定義しますModelAdmin

action_change.js

(function($){   
    $(function(){
        $(document).ready(function() {
            $('#id_type').bind('keyup', type_change);           
            $('#id_action >option').show();
        });
});  
})(django.jQuery);

// based on the type, action will be loaded

var $ = django.jQuery.noConflict();

function type_change()
{
    var action_type = $('#id_type').val();
    $.ajax({
            "type"     : "GET",
            "url"      : "/action_choices/?action_type="+action_type,
            "dataType" : "json",
            "cache"    : false,
            "success"  : function(json) {
                $('#id_action >option').remove();
                for(var j = 0; j < json.length; j++){
                    $('#id_action').append($('<option></option>').val(json[j][0]).html(json[j][1]));
                }
            }           
    })(jQuery);
}

これは、あなたが尋ねたシナリオではうまくいくはずです。そして、私は以下に私の提案をしています:

models.py

type   = models.CharField(verbose_name="Expression",max_length=32, choices = (('a', 'a'), ('b', 'b'), ))
action = models.CharField(max_length=32, choices = (('', ''), ))

action_change.js(5行目)

$('#id_type').bind('change', type_change);
于 2013-02-26T05:40:47.250 に答える
1

可能なすべての選択肢を使用してフィールドを初期化する必要がありますaction。そうしないと、Djangoは、以前は存在しなかった選択肢が有効な選択肢ではないと文句を言います。

可能なすべての選択肢でフィールドを初期化し、JavaScriptを使用して、の値に応じて選択肢の表示を切り替えることをお勧めしますtype。Django adminの動的フィールドを処理するプラグインはいくつかありますが、私が見たほとんどのプラグインは、ルックアップを実行する必要のあるForeignKeyまたはManyToManyフィールドを処理します。

Mediaメタクラスを介して管理フォームにJavaScriptを追加し、それを自分で処理するのがおそらく最善です。

于 2013-02-25T12:46:47.217 に答える