5

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,

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

awesome. I knew it had to be something easy:
Don't forget to surround in a try and except TypeError block to catch issues without crashing django

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.