Django:如何使用AJAX根据其他字段下拉选项动态生成表单字段值?

时间:2018-05-11 14:22:08

标签: jquery ajax django django-forms django-views

我想基于所选的其他字段下拉列值自动填充几个表单字段。

我可以找到几个Django AJAX教程,向您展示如何使用AJAX发送和发布表单,但我不想这样做。我想在没有AJAX的情况下提交表单发布数据。所以我想我需要发送关于特定onclick动作的帖子数据,用AJAX将该帖子数据发送到我的视图/表单,然后在视图/表单中用该帖子数据做一些事情(即设置ModelChoiceField值)。

我该怎么做呢?

我想要的动态值:

  1. 根据Coin字段值填充交易价格字段。每次更改Coin字段值时,都会创建事件。
  2. 当"销售""销售"硬币字段更改填充金额(基于用户硬币的查询集)。在" Buysell"上被选中字段。
  3. models.py

     class Transactions(models.Model):
    
        user = models.ForeignKey(User, on_delete = models.CASCADE)  
        coin = models.CharField(max_length = 64) # is coin a current holding? 
        buysell = models.CharField(default = 'buy', max_length = 4)
        amount = models.DecimalField(max_digits = 13, decimal_places = 7)  
        trade_price = models.DecimalField(max_digits = 10, decimal_places = 2)
        trade_date = models.DateTimeField(auto_now = True) 
        notes = models.TextField() 
    

    forms.py

    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 = Transactions
            fields = {'buysell', 'coin', 'amount', 'trade_price'}
    

    views.py

    def add_transaction(request):
    
        print(request.method)
        print("test1")
    
        form = TransactionForm()
        if request.method == "POST":
            print("test2")
            form = TransactionForm(request.POST)
            if form.is_valid():
                print("test3")
                obj = form.save(commit = False)
                obj.user = request.user
                obj.save()
                return HttpResponseRedirect('/myportfolio/')
            else: 
                print(form.errors)
    
        return render(request, 'myportfolio/add_transaction.html', {'form': form})
    

0 个答案:

没有答案