Filter data by year and month

This commit is contained in:
JKuijperM 2026-01-16 21:39:36 +01:00
parent d6fd95146d
commit 5579d1130c
2 changed files with 54 additions and 6 deletions

View File

@ -1,4 +1,5 @@
<!DOCTYPE html>
<h1>Dashboard</h1>
<h2>Gastos por categoría</h2>
@ -9,7 +10,38 @@
<li>No hay datos</li>
{% endfor %}
<form method="get">
<label for="year">Año:</label>
<select name="year" id="year">
<option value="">Todos</option>
{% for y in year_list %}
<option value="{{ y.year }}"
{% if selected_year == y.year|stringformat:"s" %}selected{% endif %}
>
{{ y.year }}
</option>
{% endfor %}
</select>
<label for="month">Mes:</label>
<select name="month" id="month">
<option value="">Todos</option>
{% for m in months %}
<option value="{{ m }}"
{% if selected_month == m|stringformat:"s" %}selected{% endif %}
>
{{ m }}
</option>
{% endfor %}
</select>
<button type="submit">Filtrar</button>
</form>
{% for row in by_month %}
<li>{{ row.month }} → {{ row.total }}</li>
{% endfor %}
</ul>

View File

@ -5,7 +5,7 @@ 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.db.models.functions import ExtractMonth, ExtractYear
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, render, redirect
@ -108,15 +108,16 @@ def dashboard(request):
# 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)
expenses_by_yearmonth = expenses
if year:
expenses_by_yearmonth = expenses_by_yearmonth.filter(date__year=year)
month = request.GET.get('month')
if month:
expenses = expenses.filter(date__month=month)
expenses_by_yearmonth = expenses_by_yearmonth.filter(date__month=month)
by_month = (
expenses
expenses_by_yearmonth
.annotate(month=ExtractMonth('date'))
.values('month')
.annotate(total=Sum('amount'))
@ -131,7 +132,22 @@ def dashboard(request):
for row in by_month
]
year_list = (
expenses
.annotate(year=ExtractYear('date'))
.values('year')
.distinct()
.order_by('year')
)
months = list(range(1, 13))
# Send the data to the dashboard
return render(request, 'expenses/dashboard.html', {
'by_category': by_category,
'by_month': by_month_display
'by_month': by_month_display,
'year_list': year_list,
'months': months,
'selected_year': year,
'selected_month': month,
})