我想从django应用程序中传入的URL参数中解析一个日期。我想到了:
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
我的URL.conf如下所示:
url(r'^transactions/(?P<month>\d{2})/(?P<year>\d{4}/$)', views.month_transactions, name='index',),
由于'month'和'year'作为unicode字符串(year带有一个尾随的/)进入到month_事务中,所以在从原始变量创建新日期时,我一直收到类型异常。
有没有更好的方法;Python或Django中内置的一些我错过的东西?
谢谢
你让事情变得比需要的复杂多了。
month
和year
是作为字符串传递的,因此您可以只调用int(month)
和int(year)
-不需要对regex有那么多奇怪的地方。Year只在后面加上斜杠,因为您的close paren在urlconf regex中的位置不正确-它应该直接在
}
之后,就像您在month中一样。相关问题 更多 >
编程相关推荐