列表索引超出范围django

时间:2017-04-05 13:02:46

标签: python django

有人可以解释我为什么要回来list index out of range,它出现在我的视图中的两个位置,第一个位于context_data = self.get_context_data(user_id, month, year, form=form)context['month'] = calendar.month_name[month],所以有人可以解释我是什么发生在我的代码中。这是一个完整的Traceback

我的观点:

import calendar
import datetime

from django.contrib import messages
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.http import HttpResponseForbidden
from django.shortcuts import redirect, get_object_or_404
from django.views.generic.edit import FormView

from .helpers.user_util import get_user_full_name_or_user_name
from models import Rate
from statistics.forms import CommissionsMonthSelectionForm
from statistics.services import ManagerCommissionsProjectsCalculation, CommissionsAccessService


class UserSalesCommissionsView(FormView):
    template_name = "statistics/user_sales_commissions.html"
    form_class = CommissionsMonthSelectionForm
    currency = Rate.EUR

    def get(self, request, *args, **kwargs):
        user_id = self.kwargs['user_id']
        requesting_user = request.user
        if CommissionsAccessService.can_view_commissions_page(requesting_user, user_id):
            month = int(self.request.GET.get('month', datetime.datetime.now().month))
            year = int(self.request.GET.get('year', datetime.datetime.now().year))
            form = CommissionsMonthSelectionForm(initial={'year': year, 'month': month})
            context_data = self.get_context_data(user_id, month, year, form=form)
            return self.render_to_response(context_data)
        else:
            return HttpResponseForbidden('Access denied')

    def post(self, request, *args, **kwargs):
        user_id = self.kwargs['user_id']
        requesting_user = self.request.user

        if CommissionsAccessService.can_view_commissions_page(requesting_user, user_id):
            form_class = self.get_form_class()
            form = self.get_form(form_class)
            if form.is_valid():
                return self.form_valid(form, user_id)
            else:
                return self.form_invalid(form)
        else:
            return HttpResponseForbidden('Access denied')

    def form_valid(self, form, user_id=None):
        year = form.cleaned_data['year']
        month = form.cleaned_data['month']
        return redirect(self.get_success_url(user_id, month, year))

    def form_invalid(self, form):
        messages.add_message(self.request, messages.ERROR,
                             "Invalid data. Please check fields.")
        return self.render_to_response(
            self.get_context_data(form=form)
        )

    def get_success_url(self,
                        user_id=None,
                        year=datetime.datetime.now().year,
                        month=datetime.datetime.now().month):
        return reverse("vinclucms_statistics:manager_commissions_statistics", user_id) + \
               "?month=" + str(month) + "&year=" + str(year)

    def get_context_data(self,
                         user_id=None,
                         year=datetime.datetime.now().year,
                         month=datetime.datetime.now().month,
                         **kwargs):
        context = super(UserSalesCommissionsView, self).get_context_data(**kwargs)
        context['user_name'] = get_user_full_name_or_user_name(get_object_or_404(User, pk=user_id))
        context['can_view'] = True
        context['currency'] = self.currency
        context['month'] = calendar.month_name[month]
        context['year'] = year

        context['commissions'] = ManagerCommissionsProjectsCalculation.get_project_list(
            self.currency, year, month, user_id)
        return context

观看网址:

url(r'^statistics/commissions/sales/(?P<user_id>[^/]+?)/$', login_required(views.UserSalesCommissionsView.as_view()), name='user_sales_commissions')

2 个答案:

答案 0 :(得分:2)

这是get_context_data的定义:

def get_context_data(self,
                     user_id=None,
                     year=datetime.datetime.now().year,
                     month=datetime.datetime.now().month,
                     **kwargs):

以下是它的名称:

context_data = self.get_context_data(user_id, month, year, form=form)

所以2个关键字参数(yearmonth)被反转,产生calendar.month_name[2017]这样会吐出Indexerror

您应该以正确的顺序传递参数,或者在处理关键字参数时,始终指定其名称:

context_data = self.get_context_data(user_id=user_id, month=month, year=year, form=form)

这样他们的订单就不再重要了。

也可以查看PEP 3102

答案 1 :(得分:1)

month = datetime.datetime.now().month # IF Current month is April then month==4

calendar.month_name[month]

一个数组,表示当前语言环境中一年中的月份。这遵循1月的正常约定,即月号1,因此它的长度为13,而month_name [0]是空字符串。

此处:calendar.month_name[month]检查month的值应为4,因为当前月份是4月。

所以你传递String需要一个datetime对象。