django - 上下文处理器返回错误

时间:2017-02-05 08:39:07

标签: django django-templates django-context

我在context_processors.py中添加了以下功能。但是当我去索引网址时,请回复我的错误。这是一个自然错误。因为我们在索引中没有日期参数。

有没有办法阻止显示此错误?

sample_path = http://127.0.0.1:8000/reserve/2017-02-01/

def one_day_foods_NOT_PAID(request):
    user = request.user
    path = request.get_full_path()
    date = path.strip('/').split("/", 2)
    if len(date) == 0:
        year, month, day = 0
    else:
        year, month, day = date[1].split("-")
        foods = Reservation.objects.filter(order_date__startswith = 
            datetime.date(int(year), int(month), int(day))).filter(user=user)
    return {'foods':foods}

1 个答案:

答案 0 :(得分:0)

解决它:

def one_day_foods_NOT_PAID(request):
    user = request.user
    path = request.get_full_path()
    date = path.strip('/').split("/")
    try:
        year = date[1].split("-")[0]
        month= date[1].split("-")[1]
        day = date[1].split("-")[2]
        foods = Reservation.objects.filter(order_date__startswith = 
            datetime.date(int(year), int(month), int(day))).filter(user=user)
        return {'foods':foods}
    except IndexError:
        foods = None
        return {'foods':foods}