形式:
class TransactionForm(forms.ModelForm):
CHOICES = ((1, 'Buy'), (2, '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
if coin_price:
print("coin price test")
self.coin_price = coin_price
self.fields['price'] = self.coin_price
jquery片段:
$('#id_buysell').on('change', function(){
console.log("buysell");
console.log($('#id_buysell').val());
var $formData = $(this).attr("id_buysell");
console.log($formData.val());
$.ajax({
method: "GET",
url: "/myportfolio/add_transaction",
data: $formData,
});
});
$('#id_coin').on('change', function(){
console.log("coin change")
var $formData = $(this).attr("id_coin");
console.log($formData.val());
$.ajax({
method: "GET",
url: "/myportfolio/add_transaction",
data: $formData,
});
});
观看视频片段
def add_transaction(request):
print(request.method)
print("test1")
print(request.GET)
if request.method == "GET":
if request.is_ajax():
print("ajax test")
data = {
'test': "test1"
}
form = TransactionForm(user = request.user, coin_price = GetCoin("Bitcoin").price)
return JsonResponse(data)
在我的jquery函数中,我声明了
var $ formData = $(this).attr(" id_coin");
然后使用GET将其传递给视图。但是,我不确定如何在我的视图中实际获取此数据。
那我怎么能访问这个值呢?如果我想打印它以查看此值,我可以做类似这样的事情吗?:
打印(request.GET中['硬币'])
答案 0 :(得分:1)
你不能通过ajax发送数据,你需要像下面这样发送它
{key:'value',key2:'value2'}
var coin = $(this).attr("id_coin");
$.ajax({
method: "GET",
url: "/myportfolio/add_transaction",
data: {
id_coin:coin // retrrieve the value in python with the key
},
});
在您的观点中:
print(request.GET.get('coin'))
>>> # The value of coin from JS ajax