我是Django的初学者。
如果其他字段正在编辑,我需要更改表单字段的值。
因此,如果我在网络表单中键入val1
和val2
,则val3
会在按下保存按钮之前自动进行计算。
就像在MS Excel中一样,如果我具有功能为C1
的单元格=A1+B1
。当我更改A1
或B1
的值时,C1
的值将自动更改。
class DealForm(forms.ModelForm):
class Meta:
model = Deal
fields = ['status', 'val1', 'val2', 'val3']
widgets = {
'status': forms.TextInput(attrs={'class': 'form-control'}),
'val1': forms.NumberInput(attrs={'class': 'form-control'}),
'val2': forms.NumberInput(attrs={'class': 'form-control'}),
'val3': forms.NumberInput(attrs={'class': 'form-control'})
}
class Deal(models.Model):
status = models.CharField(max_length=10, db_index=True)
val1 = models.FloatField(null = True, blank=True)
val2 = models.FloatField(null = True, blank=True)
val3 = models.FloatField(null = True, blank=True)
class DealCreate(View):
def get(self, request):
form = DealForm()
return render(request, 'portfolio/deal_create.html', context={'form':form})
def post(self, request):
bound_form = DealForm(request.POST)
if bound_form.is_valid():
new_deal = bound_form.save()
return redirect(new_deal)
return render(request, 'portfolio/deal_create.html', context={'form':bound_form})
<script>
function calcCounterVol(){
var val1 = document.getElementsByName('val1').value
var val2 = document.getElementsByName('val2').value
document.getElementByName('val3').value = parseInt(val1)+parseInt(val2)}
</script>
<form>
<div class="form-row mx-1">
<div class="form-group border col-md-6">
<div class="form-row border mt-1">
<div class="form-group col-md-3">
<label>Status</label>
{{form.status}}
</div>
<div class="form-group col-md-3">
<label>Val1</label>
{{form.val1}}
</div>
<div class="form-group col-md-3">
<label>Val2</label>
{{form.val2}}
</div>
<div class="form-group col-md-3">
<label>Val3</label>
{{form.val3}}
</div>
</div>
</div>
</form>
答案 0 :(得分:0)
您可以使用javascript做到这一点。您可以通过查看页面并进行如下计算来查看元素的名称:
<script>
function calculateVal3(){
var val1 = document.getElementsByName('val1').value
var val2 = document.getElementsByName('val2').value
document.getElementByName("val3").value = parseInt(val1)+parseInt(val2)
}
</script>
将其保留在模板中。
您可以像这样在attrs属性中传递更改事件
class DealForm(forms.ModelForm):
class Meta:
model = Deal
fields = ['status', 'val1', 'val2', 'val3']
widgets = {
'status': forms.TextInput(attrs={'class': 'form-control'}),
'val1': forms.NumberInput(attrs={'class': 'form-control'}),
'val2': forms.NumberInput(attrs={'class': 'form-control','onchange':'calculateVal3()'}),
'val3': forms.NumberInput(attrs={'class': 'form-control'})
}