IndexError:元组索引超出范围 [英] IndexError: tuple index out of range

查看:1056
本文介绍了IndexError:元组索引超出范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是指 django文档的此页面写入视图。有人可以解释我做错了什么吗?还有什么可以解决的问题?

I was referring to this page of django documentation to write views. Can someone explain what I did wrong ? And what could be the solution

    self.object_list = self.get_queryset()
  File "/vagrant/projects/kodeworms/course/views.py", line 23, in get_queryset
    self.Course = get_object_or_404(Course, name=self.args[0])
  IndexError: tuple index out of range

我的views.py文件

My views.py file

# Create your views here.
from django.views.generic import ListView, DetailView
from django.shortcuts import get_object_or_404

from .models import Course, Content


class PublishedCourseMixin(object):
    def get_queryset(self):
        queryset = super(PublishedCourseMixin, self).get_queryset()
        return queryset.filter(published_course=True)


class CourseListView(PublishedCourseMixin, ListView):
    model = Course
    template_name = 'course/course_list.html'

class CourseContentListView(ListView):
    model = Content
    template_name = 'course/content_list.html'

    def get_queryset(self):
        self.Course = get_object_or_404(Course, name=self.args[0])
        return Content.objects.filter(course=self.course, published=True)

我的urls.py文件

My urls.py file

from django.conf.urls import patterns, url

from . import views

urlpatterns = patterns('',
    url(r"^$", views.CourseListView.as_view(), name="list" ),
    url(r"^(?P<slug_topic_name>[\w-]+)/$", views.CourseContentListView.as_view(), name="list"),
)


推荐答案

您正在使用 self.args [0] 这是位置参数,但是你传递一个关键字参数到你的视图。

You are using self.args[0] which is for positional arguments, but you are passing in a keyword argument to your view.

由于你没有位置参数 self.args 是一个零长度的元组,这就是为什么你得到这个例外。

As you have no positional arguments self.args is a zero-length tuple which is why you get that exception.

你应该使用 self.kwargs [ 'slug_topic_name'] 因为你的url中有一个关键字参数。

You should be using self.kwargs['slug_topic_name'] since you have a keyword argument in your url.

这篇关于IndexError:元组索引超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆