/ add_post / list索引的IndexError超出范围

时间:2016-01-05 01:23:02

标签: python django

我不知道为什么我会收到这个错误,我最近在我的媒体文件上放了if和else方法来捕捉一些错误,现在我得到了一个全新的错误。 这是我的代码。

media.py

    import json
    from goose import Goose

    def extract(url):
        g = Goose()
        article = g.extract(url=url)
        if article.top_image is None:
            return "hello"
        else:
            resposne = {'image':article.top_image.src}
            return article.top_image.src

views.py

class PostCreateView(CreateView):
     model = Post
     form_class = PostForm
     template_name = 'main/add_post.html'

     def form_valid(self, form):
            self.object = form.save(commit=False)
            # any manual settings go here
            self.object.moderator = self.request.user
            self.object.image = extract(self.object.url) 

            self.object.save()
            return HttpResponseRedirect(reverse('post', args=[self.object.slug]))

     @method_decorator(login_required)
     def dispatch(self, request, *args, **kwargs):

            return super(PostCreateView, self).dispatch(request, *args, **kwargs)

1 个答案:

答案 0 :(得分:0)

您的部分top_image可能没有定义src个属性。你可以这样检查:

def extract(url):
    g = Goose()
    article = g.extract(url=url)
    if article.top_image is None:
        return "hello"
    else:
        if article.top_image.src is None:
            return "hello"
        else:
            resposne = {'image':article.top_image.src}
            return article.top_image.src