2017-12-16 14 views
1

私のシナリオ:Django Admin、別の選択に応じて選択オプションを設定する方法

私は3つのテーブル、カテゴリ、サブカテゴリ、製品を持っています。 新製品を挿入しながら、2つの選択ボックス

1がある)1は、選択されたカテゴリのために(その作業)

2)第2は、第1の選択に関連するべき、サブカテゴリのためです。サブカテゴリ・テーブルからデータをフェッチする必要があります。

サブカテゴリテーブルのカテゴリIDは外部キーです。 私は初心者です。誰か助けてください。

+0

は私の答えをチェック働いたということでしょうか? – Satendra

+0

申し訳ありませんが、それはうまくいきませんでした。 onchangeはどのように動作し、どこから関数呼び出しが行われるかは、事前に感謝します。 – Binayak

+0

私は統合の全体のセットを掲示しました、あなたはまだこれを実装しましたか?どこに問題があるのですか? – Satendra

答えて

1

You will have to use some JS library i prefer JQuery.

このサブカテゴリフィールドを埋めるには、jsonデータで応答するビューを作成する必要があります。 urls.pyで

from django.http import HttpResponse 
import json 

def get_subcategory(request): 
    id = request.GET.get('id','') 
    result = list(Subcategory.objects.filter(category_id=int(id)).values('id', 'name')) 
    return HttpResponse(json.dumps(result), content_type="application/json") 

は、ビューに到達するためのパターンを追加する必要があります。

url(r'^/getSubcategory/$', views.get_subcategory) 

今、あなたは、いくつかのJSを追加するには、製品のアプリケーションのためのDjangoの管理者のchange_from.htmlをオーバーライドする必要が魔法を行うコード。あなたのchange_form.html

your_project 
    |-- your_project/ 
    |-- myapp/ 
    |-- templates/ 
      |-- admin/ 
       |-- myapp/ 
        |-- change_form.html <- do not misspell this 

Note: The location of this file is not important. You can put it inside your app and it will still work. As long as its location can be discovered by django. What's more important is the name of the HTML file has to be the same as the original HTML file name provided by django.

、このような書き込み代:

{% extends "admin/change_form.html" %} 

{% block extrahead %} 
    {{ block.super }} 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
    <script type="text/javascript" charset="utf-8"> 
     $(function(){ 
      // inspect html to check id of category select dropdown. 
      $(document).on('change', "select#id_category", function(){ 
       $.getJSON("/getSubcategory/",{id: $(this).val()}, function(j){ 
        var options = '<option value="">---------</option>'; 
        for (var i = 0; i < j.length; i++) { 
         options += '<option value="' + j[i].id + '">' + j[i].name + '</option>'; 
        } 
        // inspect html to check id of subcategory select dropdown. 
        $("select#id_subcategory").html(options); 
       }); 
      }); 
     }); 
    </script> 
{% endblock %} 
# Create a JS file and put this second script tag in it, that way will be easier to maintain your template. 
+0

@ User9106216ここにコメントを追加することができます。 – Satendra

+0

申し訳ありませんが、申し訳ありませんが、フィルタリングが機能していない、私はすべての要求をマージしました。 – Binayak

+0

OK、私はあなたのプロジェクトをクローンし、自分のローカルで実行します。 – Satendra

関連する問題