Django自动完成光 - FK字段结果未转发

时间:2016-11-14 20:03:26

标签: django django-autocomplete-light

我正在跟随DAL documentation向我的表单中添加一个已过滤的字段,但转发无法将一个字段连接到另一个字段:

Forms.py

class PurchaseForm(forms.ModelForm):

    commodity = forms.ModelChoiceField(
        queryset=Commodity.objects.all(),
        widget=autocomplete.ModelSelect2(url='commodity-autocomplete'),
        required=False,
    )

    class Meta:
        model = Purchase
        fields = ["variety"]
        widgets = {
            'variety': autocomplete.ModelSelect2(url='variety-autocomplete', forward=['commodity'],   
        }

Views.py

class VarietyAutocompleteView(autocomplete.Select2QuerySetView):
    def get_queryset(self):
        qs = Variety.objects.all()

        commodity = self.forwarded.get('commodity', None)
        print("Commodity:" + str(commodity))
        if commodity:
            qs = qs.filter(commodity=commodity)

        if self.q:
            qs = qs.filter(name__istartswith=self.q)

        return qs

我希望我的Variety选项可以通过它们与Commodity对象的外键关系进行过滤。两个自动填充字段都可以正常使用,但commodity字段中的选项不会转发到VarietyAutocompleteView(我的打印命令会打印Commodity:None)。这可能是因为我传递了一个外键对象吗?或者我是否以某种方式错误地设置了它?

1 个答案:

答案 0 :(得分:1)

我不得不废弃DAL并转移到Bootstrap Combobox。如果您使用的是Bootstrap库,那么它实际上很容易实现。

这就是它的设置方式:

将类combobox添加到选择小部件:

<强> forms.py

from django import forms

from Business.models import Company, Branch
from .models import Variety

class PurchaseForm(forms.ModelForm):

    variety = forms.ModelChoiceField(
        queryset=Variety.objects.all(),
        widget=forms.Select(attrs={'class': 'combobox'}),
        required=False
    )

    class Meta:
        model = Purchase
        fields = [
            "invoice", "contract_date", ...
        ]

然后,插入最简单的javascript片段:

<强> inventory_report.html

....

<td style="padding-bottom: 10px">
    <div>Supplier:</div>
    <div>{{ view.purchase_form.supplier }}</div>
</td>

....
{% block scripts %}
    <script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
    <script type="text/javascript" src="{% static 'js/bootstrap-combobox.js' %}"></script>

        $(document).ready(function(){

            // Set Text Autofields on New Contract
           $('.combobox').combobox();

        });

    </script>
    {{ view.purchase_form.media }}
{% endblock %}

这就是它的全部内容。