加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python从django url参数解析int

发布时间:2020-12-20 11:28:13 所属栏目:Python 来源:网络整理
导读:我想在我的 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.o
我想在我的 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,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字符串进入month_transactions(年份带有尾随/),因此在从原始变量创建新日期时,我不断获得Type异常.

有没有更好的方法;我错过了内置于Python或Django中的东西?

谢谢,

解决方法

你的事情比他们需要的要复杂得多.月份和年份作为字符串传递,因此您可以调用int(月份)和int(年份) – 不需要使用正则表达式的所有奇怪之处.

年份只有一个尾随斜杠,因为你的密切关注位于urlconf正则表达式中的错误位置 – 它应该直接位于}之后,就像你有一个月一样.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读