4

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,

4

1 回答 1

8

你让事情变得比他们需要的复杂得多。monthyear作为字符串传递,所以你可以调用int(month)int(year)- 不需要正则表达式的所有奇怪之处。

年份仅带有斜杠,因为您的关闭括号在 urlconf 正则表达式中的位置错误 - 它应该直接在 之后},就像您在月份一样。

于 2013-07-10T15:15:23.560 回答