简体   繁体   中英

How do I do calculations in javascript from my formset in django?

I have a doubt, what happens is that I already managed that my first form within the table could do operations and represent them.

I was also able to create a dynamic formset.

But now I have the problem that I want my formset in Django to do different calculations and represent them.

Any idea? The javascript that I placed I followed it from several tutorials, the problem becomes complex because I have to use the JS for calculations and that it is also dynamic, I do not know where to start

表单集

Forget the format, I still haven't put the HTML right... I just want to multiply the green input (quantity) by the red input (unit price), place the total in the blue input (total price), add the blue ones and represent them in the purple input (total)

Thanks for your help:D

I put the code that I was already using

add-parts-row.js

function updateEmptyFormIDs(element,totalForms){
   var thisInput=element
   var currentName=element.attr('name')

   //THIS IS WHAT PREFIX REPLACES WITH totalForms
   var newName=currentName.replace(/__prefix__/g,totalForms)

   //this is what replaces name with the number totalForms
   thisInput.attr('name',newName)

   //this is what replaces id with the totalForms number
   thisInput.attr('id',"id_"+newName)


   var newFormRow=element.closest(".form-row");
   var newRowId="row_id_"+newName
   newFormRow.attr("id",newRowId)

   newFormRow.addClass("new-parent-row")

   var parentDiv=element.parent();
   parentDiv.attr("id","parent_id_"+newName)

   var inputLabel=parentDiv.find("label")
   inputLabel.attr("for","id_"+newName)

   return newFormRow

   }

// you click the button and it adds more rows

$( "#add_more" ).click(function(e) {
  var formId="id_form-TOTAL_FORMS"
  var emptyRow=$("#empty-row").clone();
  emptyRow.attr("id",null)
  var totalForms=parseInt($('#'+formId).val());
  var newFormRow;

 
  emptyRow.find("input, checkbox").each(function(){
        newFormRow=updateEmptyFormIDs($(this),totalForms)
  })

  $(".form-row:last").after(newFormRow)
  $('#'+formId).val(totalForms+1);
});

calculos.js


function multiplicar(){


    var quantity=parseInt(document.getElementById('id_quantity').value);
    var unit_price=document.getElementById('id_unit_price').value;
    var total_price=document.getElementById('id_total_price');
    total_price.value=quantity*unit_price;

}



function taxes_free() {
    var total_price=document.getElementById('id_total_price').value;
    var total=document.getElementById('id_total');

    if (document.getElementById('id_tax_free').checked){
      var libre_impuestos = total_price*0.24;
      total.value=total_price - libre_impuestos;
      }

    }


function totales(){

    var descuento=document.getElementById('id_descuento').value;
    var total=document.getElementById('id_total').value;
    totales=(descuento * total) / 100;
    document.getElementById("id_total").value = totales;

}

presupuestos-forms.html


                                            <!-- Parts -->
                                            <h3>Partes</h3>
                                            <section>
                                            <div>
                                                <form action='' method="POST">
                                                    {% csrf_token %}
                                                    <div class="row">
                                                        <div class="col-12">
                                                            <div class="card">
                                                                <div class="card-body">

                                                                    <h4 class="card-title">Partes</h4>
                                                                    <p class="card-title-desc">Agrega las partes que se incluirán</p>

                                                                    <div class="table-responsive">
                                                                        <table class="table table-bordered table-nowrap align-middle">
                                                                            <thead class="table-info">
                                                                              <tr>
                                                                                <th scope="col">Código</th>
                                                                                <th scope="col">Descripción</th>
                                                                                <th scope="col">Cantidad</th>
                                                                                <th scope="col">Precio Unitario</th>
                                                                                <th scope="col">Precio Total</th>
                                                                                <th scope="col">Libre de Impuestos</th>
                                                                                <th scope="col">Agrega Fila</th>
                                                                              </tr>
                                                                            </thead>
                                                                            <tbody>
                                                                              <tr>
                                                                                <td>
                                                                                    {{presupuestosparteform.codigo}}
                                                                                </td>
                                                                                <td>
                                                                                  {{presupuestosparteform.descripcion}}
                                                                                </td>
                                                                                <td>
                                                                                  {{presupuestosparteform.quantity}}
                                                                                </td>
                                                                                <td>
                                                                                  {{presupuestosparteform.unit_price}}
                                                                                </td>
                                                                                <td>
                                                                                  {{presupuestosparteform.total_price}}
                                                                                </td>
                                                                                <td>
                                                                                    <div>
                                                                                        {{presupuestosparteform.tax_free}}
                                                                                    </div>
                                                                                </td>
                                                                                <td>
                                                                                  <input type="button" class="btn btn-block btn-default" id="add_more"  value="+" />
                                                                                </td>

                                                                              </tr>

                                                                                {{ formset.management_form }}
                                                                                 {% for form in formset %}
                                                                              <tr id="formset" class="form-row">
                                                                                   <td>
                                                                                        {% render_field form.codigo class="form-control" %}
                                                                                    </td>
                                                                                    <td>
                                                                                        {% render_field form.descripcion class="form-control" %}
                                                                                    </td>
                                                                                    <td>
                                                                                        {% render_field form.quantity class="form-control" %}
                                                                                    </td>
                                                                                    <td>
                                                                                        {% render_field form.unit_price class="form-control" %}
                                                                                    </td>
                                                                                    <td>
                                                                                        {% render_field form.total_price class="form-control" %}
                                                                                    </td>
                                                                                    <td>
                                                                                        {% render_field form.tax_free class="form-check-input" %}
                                                                                    </td>

                                                                                  </tr>
                                                                                {% endfor %}


                                                                            </tbody>
                                                                          </table>

                                                                        <!--el row duplicado en el formset con empty-row-->

                                                                          <div class="form-row" id="empty-row">
                                                                              <table class="table table-bordered table-nowrap align-middle">
                                                                                 <td>
                                                                                     {% render_field formset.empty_form.codigo class="form-control" %}
                                                                                 </td>
                                                                                  <td>
                                                                                      {% render_field formset.empty_form.descripcion class="form-control" %}
                                                                                  </td>
                                                                                  <td>
                                                                                      {% render_field formset.empty_form.quantity class="form-control" %}
                                                                                  </td>
                                                                                  <td>
                                                                                      {% render_field formset.empty_form.unit_price class="form-control" %}
                                                                                  </td>
                                                                                  <td>
                                                                                      {% render_field formset.empty_form.total_price class="form-control" %}
                                                                                  </td>
                                                                                  <td>
                                                                                      {% render_field formset.empty_form.tax_free class="form-check-input" %}
                                                                                  </td>

                                                                              </table>
                                                                          </div>

                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div> <!-- end col -->

                                                    </div> <!-- end row -->

                                                    <div class="row justify-content-end">
                                                        <div class="col-md-3">
                                                            <div class="mb-3">
                                                                <label>Discount</label>
                                                                {{presupuestosparteform.descuento}}
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div class="row justify-content-end">
                                                        <div class="col-md-3">
                                                            <div class="mb-3">
                                                                <label><strong>TOTAL:</strong></label>
                                                                {{presupuestosparteform.total}}
                                                            </div>
                                                        </div>
                                                    </div>

                                                </form>
                                              </div>
                                        </section>

You can try django-calculation library to perform that type of calculation easily.

Example:

Forms Declaration

class OrderForm(forms.ModelForm):
    total = forms.DecimalField(
        # using SumInput a SummaryInput abstraction
        widget=calculation.SumInput('subtotal')
    )
    class Meta:
        model = Order
        fields = ['date', 'customer']

class OrderDetForm(forms.ModelForm):
    quantity = forms.DecimalField()
    price = forms.DecimalField()
    subtotal = forms.DecimalField(
        widget=calculation.FormulaInput('quantity*price')
    )
    class Meta:
        model = OrderDet
        fields = ['product', 'price', 'quantity', 'subtotal']

# formset definition
OrderDetFormSet = forms.inlineformset_factory(Order, OrderDet, OrderDetForm)

Template

Make sure to add the call to {{ form.media }} .

<form method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit">
</form>

{{ form.media }}

You will not need to write JavaScript code, the library is responsible for mapping the fields and executing the specified formula.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM