我想基于所选的其他字段下拉列值自动填充几个表单字段。
我可以找到几个Django AJAX教程,向您展示如何使用AJAX发送和发布表单,但我不想这样做。我想在没有AJAX的情况下提交表单发布数据。所以我想我需要发送关于特定onclick动作的帖子数据,用AJAX将该帖子数据发送到我的视图/表单,然后在视图/表单中用该帖子数据做一些事情(即设置ModelChoiceField值)。
我该怎么做呢?
我想要的动态值:
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})