2013-07-10 57 views
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中的東西,我錯過了?

感謝,

回答

6

你正在做的事情要複雜得多,他們需要。 monthyear作爲字符串傳遞,因此您可以撥打int(month)int(year) - 不需要使用正則表達式的所有奇怪。

僅在一年後纔會出現尾部斜線,因爲您的近距離paren在urlconf正則表達式中出現錯誤的位置 - 它應該緊跟}之後,就像您一個月一樣。

+0

真棒。我知道這一定很容易: – shelbydz