Django:如何基于所选的其他表单字段选项更改具有不同Queryset的表单字段选择选项?

时间:2018-05-29 09:55:44

标签: python django

当用户选择" Sell"时,我希望我的硬币字段的查询集发生变化。在" BuySell"使用jquery的下拉选项。下拉列表更改后,我发送一个带有AJAX的Get请求,在我的视图中选择该请求,然后重新加载表单,这是我在TransactionForm的init方法中覆盖默认硬币字段查询集的地方。

这没有按预期工作,没有任何改变硬币下拉选项的任何事情,我没有错误(包括在检查元素时在网络选项卡中)。

我想知道这是否与我在这里调用表单的方式有关:

form = TransactionForm(user = request.user, coin_price = GetCoin("Bitcoin").price)

和表单init方法:

def __init__(self, coin_price = None, user = None, *args, **kwargs):    
        super(TransactionForm, self).__init__(*args, **kwargs)

        if user:

            self.user = user
            qs_coin = Portfolio.objects.filter(user = self.user).values('coin').distinct()
            print("qs_coin test: {}".format(qs_coin))
            self.fields['coin'].queryset = qs_coin

完整代码:

表单

class TransactionForm(forms.ModelForm):     
    CHOICES = (('Buy', 'Buy'), ('Sell', 'Sell'),)

    coin = forms.ModelChoiceField(queryset = Coin.objects.all()) 
    buysell = forms.ChoiceField(choices = CHOICES)

    field_order = ['buysell', 'coin', 'amount', 'trade_price']

    class Meta:
        model = Transaction
        fields = {'buysell', 'coin', 'amount', 'trade_price'}

    def __init__(self, coin_price = None, user = None, *args, **kwargs):
        super(TransactionForm, self).__init__(*args, **kwargs)
        print("Transaction form init: ", user, coin_price)

        if user:
            self.user = user
            qs_coin = Portfolio.objects.filter(user = self.user).values('coin').distinct()
            print("qs_coin test: {}".format(qs_coin))
            self.fields['coin'].queryset = qs_coin

观看片段

def add_transaction(request):

    if request.method == "GET":
        if request.is_ajax():
            print("ajax test")

            #print(request.GET.get)
            print(request.GET.get('coin'))
            print(request.GET.get('buysell'))

            view_coin = None 
            if request.GET.get('coin'):
                view_coin = GetCoin(request.GET.get('coin')).price

            data = {
                'view_buysell': request.GET.get('buysell'),
                'view_coin': request.GET.get('coin'),
                'view_amount': "test",
                'view_price': view_coin
            }

            form = TransactionForm(user = request.user, coin_price = GetCoin("Bitcoin").price)

            return JsonResponse(data)

jquery的

$('#id_buysell').on('change', function(){

        console.log("buysell");

        var $id_buysell = $('#id_buysell').val();
        console.log($id_buysell);

        $.ajax({
            method: "GET",
            url: "/myportfolio/add_transaction",
            dataType: 'json',
            data: { buysell: $id_buysell },
            success: function(data, status) {
                console.log("SUCCESS:");
                console.log(data);
                console.log(data['view_buysell']);

            },
            error: function(response) {

            }
        });

    });

$('#id_coin').on('change', function(){

    console.log("test")
    console.log("coin change")

    var $id_coin = $('#id_coin').find("option:selected").text();
    console.log($id_coin);

    $.ajax({
        method: "GET",
        url: "/myportfolio/add_transaction",
        dataType: 'json',
        data: {coin: $id_coin},
        success: function(data, status) {
            console.log("SUCCESS:");
            console.log(data);
            console.log(data['view_buysell']);

            $("#id_trade_price").val(data['view_price']);
        },
        error: function(response) {

        }
    });

1 个答案:

答案 0 :(得分:0)

我想做的事情是不必要的。

实现此目的的正确方法是将所有查询集转换为列表,然后将它们传递给JsonResponse中的jquery。然后我可以在我的jquery中清除并加载这些列表作为选择选项。

更新代码:

视图

if request.method == "GET":
        if request.is_ajax():
            print("ajax test")

            #print(request.GET.get)
            print(request.GET.get('coin'))
            print(request.GET.get('buysell'))

            view_coin = None 
            if request.GET.get('coin'):
                view_coin = GetCoin(request.GET.get('coin')).price

            coin_sell_options = Portfolio.objects.filter(user = request.user).values('coin').distinct()
            coin_buy_options = Coin.objects.all()

            coin_buy_options = [x.coin for x in coin_buy_options]

            coins = [key['coin'] for key in coin_sell_options]
            coin_amount = list(Portfolio.objects.filter(user = request.user, coin__in = coins).values_list('amount', flat = True))
            coin_amount = [str(x) for x in coin_amount]
            print(coin_amount)

            data = {
                'view_buysell': request.GET.get('buysell'),
                'view_coin': request.GET.get('coin'),
                'view_amount': "test",
                'view_price': view_coin,
                'coin_sell_options': list(coin_sell_options),
                'coin_buy_options': list(coin_buy_options),
                'coin_amounts': coin_amount
            }

            form = TransactionForm(user = request.user, coin_price = GetCoin("Bitcoin").price)

            return JsonResponse(data)

jquery的

$('#id_buysell').on('change', function(){

            console.log("buysell");

            var $id_buysell = $('#id_buysell').val();
            console.log($id_buysell);

            $.ajax({
                method: "GET",
                url: "/myportfolio/add_transaction",
                dataType: 'json',
                data: { buysell: $id_buysell },
                success: function(data, status) {
                    console.log("SUCCESS:");
                    console.log(data);
                    console.log(data['view_buysell']);

                    $("#id_coin").empty();                  

                    var items = data['coin_options'];

                    console.log(items);

                    $.each(items, function(key, value) {
                        console.log(value.coin);
                        $("#id_coin").append(new Option(value.coin));
                    });


                },
                error: function(response) {

                }
            });

        });