Added filter by year and month

This commit is contained in:
JKuijperM 2026-01-15 15:28:36 +01:00
parent ccc48bd50d
commit d6fd95146d
2 changed files with 51 additions and 1 deletions

View File

@ -8,4 +8,8 @@
{% empty %}
<li>No hay datos</li>
{% endfor %}
{% for row in by_month %}
<li>{{ row.month }} → {{ row.total }}</li>
{% endfor %}
</ul>

View File

@ -1,12 +1,30 @@
from datetime import date
from .models import Expense
from .forms import ExpenseForm
from django.db.models import Sum
from django.contrib.auth import login
from django.utils.ipv6 import is_valid_ipv6_address
from django.db.models.functions import ExtractMonth
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, render, redirect
MONTHS = {
1:'ENERO',
2:'FEBRERO',
3:'MARZO',
4:'ABRIL',
5:'MAYO',
6:'JUNIO',
7:'JULIO',
8:'AGOSTO',
9:'SEPTIEMBRE',
10:'OCTUBRE',
11:'NOVIEMBRE',
12:'DICIEMBRE'
}
@login_required
def expense_list(request):
expenses = Expense.objects.filter(owner=request.user)
@ -84,8 +102,36 @@ def dashboard(request):
expenses = Expense.objects.filter(owner=request.user)
# Querysets
by_category = (expenses.values('category__name').annotate(total=Sum('amount')))
# Get year, if is empty, use current year
year = request.GET.get('year')
year_filter = year if year else date.today().year
expenses = expenses.filter(date__year=year_filter)
month = request.GET.get('month')
if month:
expenses = expenses.filter(date__month=month)
return render(request, 'expenses/dashboard.html', {'by_category': by_category})
by_month = (
expenses
.annotate(month=ExtractMonth('date'))
.values('month')
.annotate(total=Sum('amount'))
.order_by('month')
)
by_month_display = [
{
'month': MONTHS[row['month']],
'total': row['total'],
}
for row in by_month
]
return render(request, 'expenses/dashboard.html', {
'by_category': by_category,
'by_month': by_month_display
})