3
我想在我的django應用程序中解析傳入URL參數的日期。我想出了:Python從django url參數中解析int
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_transactions爲unicode字符串(一年自帶一個尾隨/)從原始變量創建新日期時,我不斷收到類型異常。
有沒有更好的方法;內置於Python或Django中的東西,我錯過了?
感謝,
真棒。我知道這一定很容易: – shelbydz