繁体   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