我想在我的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
Run Code Online (Sandbox Code Playgroud)
我的URL.conf看起来像:
url(r'^transactions/(?P<month>\d{2})/(?P<year>\d{4}/$)', views.month_transactions, name='index',),
Run Code Online (Sandbox Code Playgroud)
由于'month'和'year'作为unicode字符串进入month_transactions(年份带有尾随/),因此在从原始变量创建新日期时,我不断获得Type异常.
有没有更好的方法; 我错过了内置于Python或Django中的东西?
谢谢,
你的事情比他们需要的要复杂得多.month并且year作为字符串传递,所以你可以调用- int(month)并且int(year)不需要与正则表达式的所有奇怪性.
年份只有一个尾随斜杠,因为你的密切关注位于urlconf正则表达式的错误位置 - 它应该直接在}你之后的月份之后.
| 归档时间: |
|
| 查看次数: |
6346 次 |
| 最近记录: |