'Django Model Method access from template
I cannot render in a template the method get_total_hoy, what it does is get the total sales of products of the currrent day;
class VentaProductos(models.Model):
producto = models.ForeignKey(
Productos, null= True, on_delete=models.SET_NULL)
medio_de_venta = models.ForeignKey(MediosVenta, null=True, blank=False, on_delete=models.SET_NULL)
precio_de_venta = models.FloatField(null=True, blank=True)
fecha_venta = models.DateField(blank=False, null=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
vendido_por = models.CharField(max_length=20, null=False, blank=False)
class Meta:
verbose_name_plural = "Venta de Productos"
ordering = ["-id"]
def __str__(self):
return f"{self.producto.nombre}"
def get_total_hoy(self):
today = timezone.now()
total = VentaProductos.objects.filter(fecha_venta=today).aggregate(total = Sum('precio_de_venta'))
total_productos = total['total']
print(total_productos)
return total_productos
in my template I have the following table:
<h2>Ventas de hoy</h2>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Nombre</th>
<th scope="col">Precio</th>
<th scope="col">Fecha</th>
<th scope="col">vendido por</th>
</tr>
</thead>
<tbody>
{% for producto in ventaproductos_list %}
<tr>
<th scope="row">{{forloop.counter}}</th>
<td>{{producto.producto}}</td>
<td>${{producto.precio_de_venta}}</td>
<td>{{producto.fecha_venta}}</td>
<td>{{producto.vendido_por}}</td>
</tr>
{% endfor %}
<tr>
<td>${{ventaproductos.get_total_hoy}}</td>
</tr>
</tbody>
</table>
I'm trying to display that total at the end of the table.
My understanding is that if my method does not required extra parameters there is no need to access it as context in the view and I can access directly. Anyway I this is my current view (if it helps):
class Home(ListView):
model = VentaProductos
template_name= 'main/home.html'
def get_queryset(self):
today = timezone.now()
return VentaProductos.objects.filter(fecha_venta = today)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
