I'd like to parse a date from incoming URL parameters in my django application. I came up with:
def month_transactions(request, month, year):
current_month = calculate_current_month(month, year)
next_month = calculate_next_month(current_month)
debit_transactions = Transaction.objects.filter(is_credit=False,
due_date__range=(current_month, next_month))
credit_transactions = Transaction.objects.filter(is_credit=True,
due_date__range=(current_month, next_month))
return render(request, 'finances/index.html', {
'debits': debit_transactions,
'credits': credit_transactions,
})
def calculate_current_month(month, year):
current_month = re.match('\d{2}', month)
current_year = re.match('\d{4}', year)
return_month = datetime.date(
int(current_year.group()), int(current_month.group()), 1)
return return_month
Where my URL.conf looks like:
url(r'^transactions/(?P<month>\d{2})/(?P<year>\d{4}/$)', views.month_transactions, name='index',),
Since 'month' and 'year' come in to month_transactions as unicode strings (year comes with a trailing /) I kept getting Type exceptions when creating a new date from the raw variables.
Is there a better approach; something built into Python or Django that I missed?
Thanks,
You're making things much more complicated than they need to be. month
and year
are passed as strings, so you can just call int(month)
and int(year)
- no need for all that strangeness with the regexes.
Year only comes in with a trailing slash because your close paren is in the wrong place in the urlconf regex - it should be directly after the }
, as you have for month.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With