Adjunté el HTML en la pregunta de la foto: cómo obtener todos los datos de precio, cantidad de HTML en js y multiplicarlo en consecuencia y agregarlo a HTML en Django. alguien me ayuda
const x = document.getElementById("qty").innerHTML; const y = document.getElementById("price").innerHTML; const z = document.getElementById("total"); function calculator(qty, price) { let lowercase = price.toLowerCase(); const remove_price_string = lowercase.replace("only", ""); console.log(remove_price_string); let total = remove_price_string * qty; console.log(total); } calculator(x, y);Voy a suponer que cada factura es un objeto modelo de Django. La forma más fácil de hacer este cálculo en Django es agregarlo como una función a su modelo :
# models.py from django.db import models import re class Bill(models.Model): full_name = models.CharField(max_length=30) food_name = models.CharField(max_length=30) qty = models.IntegerField() # Ideally, you would represent the price using # a DecimalField. # price = models.DecimalField(decimal_places=2) # only = models.BooleanField(default=False) # However, you said you're using a string instead. price = models.CharField(max_length=20) # If price was a DecimalField, you could do a simple # calculation. #def total(self): # return self.qty * self.price # However, since it's a string, you'll have to # convert it to a whole number first. def total(self): """Computes the total bill from the quantity and price.""" # Remove non-numeric strings like 'only' # from the price. Warning: this will remove # decimal points too, so it only works with # whole numbers as prices. price = re.sub("[^0-9]", "", self.price) # Convert it to a whole number so we can do # math on it. price = int(price) # Return the calculated result return self.qty * pricePuede llamar a esta función en su plantilla escribiendo su nombre, sin paréntesis:
<td id="total">{{ bill.total }}</td> Tenga cuidado con la forma en que representa las monedas. Si necesita representar cantidades fraccionarias, use un DecimalField con un número apropiado de lugares decimales establecidos; de lo contrario, use un IntegerField . Nunca debe usar un FloatField para representar monedas, ya que no siempre almacena una representación exacta de un monto de moneda.