Django:如何根据所选的其他表单字段选项更改具有不同查询集的表单字段选择选项? [英] Django: How to change form field select options with different Querysets, based on other form field options selected?
问题描述
当用户在jquery的"BuySell"下拉选项中选择"Sell"时,我希望更改硬币字段的查询集.更改下拉列表后,我将使用AJAX发送获取请求",在我的视图中接收该请求,然后重新加载表单,这是我在TransactionForm的init方法中覆盖默认硬币字段查询集的地方.
I want the queryset of my coin field to change when a user selects "Sell" in the "BuySell" dropdown option with jquery. Once the dropdown is changed I send a Get Request with AJAX, pick that request up in my view and then reload the form, which is where I override the default coin field queryset in my TransactionForm's init method.
这无法正常工作,更改硬币下拉选项没有任何反应,并且我没有收到任何错误(包括检查元素时在网络"标签中的错误).
This isn't working as expected, nothing happens to change the coin dropdown options and I get no errors (including in the Network tab when I inspect element).
我想知道这是否与我在此处调用表单的方式有关:
I wonder if this is something to do with the way I'm calling my form here:
form = TransactionForm(user = request.user, coin_price = GetCoin("Bitcoin").price)
以及表单初始化方法:
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) {
}
});
推荐答案
我试图做的事情是不必要的.
What I was trying to do was unnecessary.
实现此目的的正确方法是将我所有的查询集都转换为列表,然后将它们传递给JsonResponse中的jquery.然后,我可以根据需要在需要时清除并加载这些列表作为jquery中的选择选项.
The correct way to achieve this was to convert all of my querysets into lists and then pass them to jquery in JsonResponse. Then I can clear and load these lists as select options in my jquery as and when I need.
更新的代码:
观看次数
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) {
}
});
});
这篇关于Django:如何根据所选的其他表单字段选项更改具有不同查询集的表单字段选择选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!