簡體   English   中英

我如何關聯 2 Django ChoiceFileds

[英]How i can to relate 2 Django ChoiceFileds

我的項目有問題。 我想在 models.py 文件中創建一個 ChoiceField 作為類別和子類別。 嗯,一定是我根據地方的索引選擇了第一選擇第二。 比如像汽車和它的模型,按照我在First ChoiceField中選擇的品牌,你在第二個字段中看它的模型。 在姜戈。

歡迎使用堆棧溢出! 我過去通過使用一些 jQuery 創建我自己的小部件CategorizedSelect來完成此操作。 這是代碼和注釋:

my_app/widgets.py : 從 django.forms.widgets 導入選擇

class CategorizedSelect(Select):
    """
    This widget takes a dict of categories and a list of dicts for items.
    It renders two drop downs, the first of the categories, which then
    populates the second drop down with the items in that category via
    the jQuery chained library.

    For example:

    # Prepare data for chained dropdown field for security
    intl_stocks = Security.objects.filter(
        active=True,
        security_type__short_name="INT",
    ).select_related(
        'exchange',
    ).order_by(
        'exchange__name', 'name',
    )

    exchanges, securities = OrderedDict(), []

    for intl_stock in intl_stocks:
        exchanges[intl_stock.exchange.id] = intl_stock.exchange.name
        securities += [{'category_id': intl_stock.exchange.id, 'id': intl_stock.id, 'name': intl_stock.name}]

    security = forms.ModelChoiceField(
        queryset=Security.objects.none(),
        widget=CategorizedSelect(
            categories=exchanges,
            items=securities,
        ),
    )
    """
    template_name = 'my_app/widgets/categorized_select.html'

    def __init__(self, attrs=None, categories=None, items=None):
        super().__init__(attrs)
        self.categories = categories
        self.items = items

    def get_context(self, name, value, attrs):
        context = super().get_context(name, value, attrs)
        context['categories'] = self.categories
        context['items'] = self.items

        return context

my_app/templates/my_app/widgets/categorized_select.html

<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-chained/1.0.1/jquery.chained.min.js"></script>
<select id="chain_select_{{ widget.name }}_id" name="chain_select_{{ widget.name }}" class="form-control">
    <option value="">--</option>
    {% for id, name in categories.items %}
        <option value="{{ id }}">{{ name }}</option>
    {% endfor %}
</select>
<br>
<select name="{{ widget.name }}"{% include "django/forms/widgets/attrs.html" %}>
    <option value="">--</option>
    {% for item in items %}
        {% comment %}
        If we match the initial value set by the Django form, we need to
        set SELECTED on the child, and use jQuery to force the category parent
        drop down to the proper selection as well. We will force item.id to a 
        string since the widget.value.0 is always a string.
        {% endcomment %}
        {% if item.id|stringformat:"i" == widget.value.0 %}
            <option value="{{ item.id }}" class="{{ item.category_id }}" SELECTED>{{ item.name }}</option>
            <script>
                var selected_category_id = {{ item.category_id }}
            </script>
        {% else %}
            <option value="{{ item.id }}" class="{{ item.category_id }}">{{ item.name }}</option>
        {% endif %}
    {% endfor %}
</select>
<script>
$("#{{ widget.attrs.id }}").chained("#chain_select_{{ widget.name }}_id");

if(selected_category_id) {
    $('#chain_select_{{ widget.name }}_id').val(selected_category_id).change();
    $('#chain_select_{{ widget.name }}_id').prop("disabled", true);
    $('#{{ widget.attrs.id }}').prop("disabled", true);
}
</script>

評論中的示例顯示了如何對一組國際股票進行此操作; 國際交易所是類別,股票本身就是項目。 祝你好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM