当用户在表单中填写数据时计算输入字段 - Django 模型表单

Calculate Input Fields while user is filling data in form - Django Model Form

我有一个用户表单,通过它我可以将数据保存到数据库中。

我希望在填写表格时自动计算某些字段。

例如净重 = 毛重 - 等级重量 等等。

我还想为 LOADINGUNLOADINGDEDUCTION 等字段添加单选按钮,等等。当用户选择给定的选项之一时,将计算值。

设计我想要的表单类型,我只是不知道如何使用 Django 来实现:

我正在使用 Django 模型表单。

Models.py

class PaddyPurchase(models.Model):
    ref_no = models.IntegerField(primary_key='true')
    token_no = models.CharField(max_length=20, unique='true')
    agent_name = models.CharField(max_length=20)
    trip_no = models.IntegerField()
    date = models.DateField()
    vehicle_no = models.CharField(max_length=10)
    bora = models.IntegerField()
    katta = models.IntegerField()
    plastic = models.IntegerField()
    farmer_name = models.CharField(max_length=30)
    farmer_address = models.CharField(max_length=40)
    farm_mob = models.CharField(max_length=10)
    gross_weight = models.IntegerField()
    tier_weight = models.IntegerField()
    net_weight = models.IntegerField()
    bora_weight = models.IntegerField()
    suddh_weight = models.FloatField()
    loading = models.IntegerField()
    unloading = models.IntegerField()
    unloading_point = models.CharField(max_length=20)
    dharamkanta_man = models.CharField(max_length=10)
    rate = models.IntegerField()
    bardana = models.CharField(max_length=7)
    gross_total = models.IntegerField()
    deduction = models.IntegerField()
    kanta = models.IntegerField()
    hemali = models.IntegerField()
    our_vehicle_rent = models.IntegerField()
    agent_commission = models.IntegerField()
    other_amt = models.IntegerField()
    other_remarks = models.CharField(max_length=50)
    advance = models.IntegerField()
    net_total = models.IntegerField()


 # For returning data in ADMIN SITE
 def __str__(self):
     return 'PaddyPurchase'

Forms.py

class PaddyPurchaseForm(forms.ModelForm):
# Code for changing DATE FORMAT (from YYYY-MM-DD to DD-MM-YYYY)
date = forms.DateField(
    widget=forms.DateInput(format='%d%m%Y'),
    input_formats=['%d-%m-%Y']
)

class Meta:
    model = PaddyPurchase
    fields = ['ref_no',
              'token_no',
              'agent_name',
              'trip_no',
              'date',
              'vehicle_no',
              'bora',
              'katta',
              'plastic',
              'farmer_name',
              'farmer_address',
              'farm_mob',
              'gross_weight',
              'tier_weight',
              'net_weight',
              'bora_weight',
              'suddh_weight',
              'loading',
              'unloading',
              'unloading_point',
              'dharamkanta_man',
              'rate',
              'bardana',
              'gross_total',
              'deduction',
              'kanta',
              'hemali',
              'our_vehicle_rent',
              'agent_commission',
              'other_amt',
              'other_remarks',
              'advance',
              'net_total'
              ]

Viwes.py

def add_record(request):

if request.method == "POST":
    form = PaddyPurchaseForm(request.POST)
    if form.is_valid():
        form.save(commit=True)
        messages.success(request, "Data Saved Successfully. - Lucky")
        return index(request)
    else:
        messages.error(request, "Error!!!")
return redirect("index")

这是JavaScript要解决的问题。 Django 可以处理 server-side,但是由于您希望这些计算在用户输入时完成,或者在 提交之前 输入信息,您需要 JavaScript处理 client-side。填写表单后,您仍然可以使用 Django 已有的内容将其发送到服务器(视图)。

那么如何用 JavaScript 做到这一点?首先给每个输入一个 id,这样你就可以在你的 JavaScript (JS) 脚本中访问它们,例如,

<input id='gross_weight' ...>
<input id='tier_weight' ...>
<input id='net_weight' ...>

接下来,使用 JS input event or a change event 检测用户何时输入了值,进行计算,然后更新表单中的值:

<script>
    // Get the input elements by targeting their id:
    const gross_input = document.getElementById('gross_weight');
    const tier_input = document.getElementById('tier_weight');
    const net_input = document.getElementById('net_weight');
 
    // Create variables for what the user inputs, and the output:
    let gross = 0;
    let tier = 0;
    let net = 0;

    // Add an event listener to 'listen' to what the user types into the inputs:
    gross_input.addEventListener('input', e => {
      gross = e.target.value;
      updateNet()
    });
    tier_input.addEventListener('input', e => {
      tier = e.target.value;
      updateNet()
    });

    // Update the value of net based on what the user inputs in for gross and tier
    function updateNet(e) {
        net = gross - tier;
        net_input.value = net;
    }
</script>

当用户提交表单时,Django 接管。