Skip to content
Advertisement

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

I have a user form through which I can save data to the database.

I want certain fields to be auto calculated while I am filling the the form.

For e.g. Net Weight = Gross Weight – Tier Weight and stuff like that.

I also want to add RADIO BUTTONS for fields like LOADING, UNLOADING, DEDUCTION, etc. where values will be calculated when user selects one of the option given.

Design of the type of form I want, I just don’t know how to make that using Django:

enter image description here

I am using Django Model Form.

Models.py

JavaScript

Forms.py

JavaScript

Viwes.py

JavaScript

Advertisement

Answer

This is a problem to be solved with JavaScript. Django can handle the server-side, but since you want these calculations to be done as the user types, or enters information before it is submitted, you need JavaScript to handle the client-side. Once the form is filled in, you can still send it to the server (the views) using what you already have with Django.

So how do you do this with JavaScript? First give each of the inputs an id, so you can access them in your JavaScript (JS) script, for example,

JavaScript

Next, use JS input event or a change event to detect when the user has inputted a value, do your calculations, and then update the values in your form:

JavaScript

When the user submits the form, Django takes over.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement