Question:
I am creating an accounting application. I created the model for the transactions as follows:
Transacciones()
consumidor
monto
tipo_monto
fecha
comentario
In the admin I made all the columns to be displayed and also the filters for each column, but I need the total of the transaction amounts to be added in a new row.
Is there any way to add this kind of thing in the admin? Add a Count
for example.
Answer:
Answering your question:
Is there any method of adding this kind of thing in the admin?
Yes.
What you have to do first is to override the ModelAdmin.changelist_view
method, what you need is a Sum
, not a Count
:
admin.py:
from django.contrib import admin
from django.db.models import Sum
from .models import Transacciones
class TransaccionesAdmin(admin.ModelAdmin):
def changelist_view(self, request, extra_context=None):
total = Transacciones.objects.aggregate(total=Sum('monto'))['total']
context = {
'total': total,
}
return super(TransaccionesAdmin, self).changelist_view(request, extra_context=context)
admin.site.register(Transacciones, TransaccionesAdmin)
You also need to override the admin template , this can be achieved by copying the template from the path contrib/admin/templates/admin/change_list.html
and pasting it into your project path templates/admin/nombre_app/transacciones/
.
It only remains to show the total
result in the template and you achieve this by showing it as you would in any other template.
templates/admin/app_name/transactions/change_list.html:
...
{% block content %}
...
{{ total }}
...
{% endblock %}
...