Django不会在try语句中重定向到404

时间:2014-04-09 16:35:12

标签: python django django-models django-views

我目前正在学习Django库,我很难过 因为我收到一个DoesNotExist错误(状态= 500)而不是404页错误, 我试过调试debug = False,但我收到的只是500状态页面。

class CategoryView(generic.ListView):
    model = Category
    template_name = 'rango/category.html'
    allow_empty = False

    try:
        def get_context_data(self, *args, **kwargs):
            context = super(CategoryView, self).get_context_data(*args, **kwargs)
            category_name = decode_url(self.kwargs['category_name_url'])
            category = Category.objects.get(name = category_name)
            pages = Page.objects.filter(category = category)
            context['category'] = category
            context['pages'] = pages
            return context   
    except Category.DoesNotExist:
        raise Http404

回溯:

  

在/ rango / category / Perl /

中的DoesNotExist      

类别匹配查询不存在。

     

回溯:文件   “/Library/Python/2.7/site-packages/django/core/handlers/base.py”in   get_response     114. response = wrapped_callback(request,* callback_args,** callback_kwargs)文件“/Library/Python/2.7/site-packages/django/views/generic/base.py”in   视图     69.返回self.dispatch(request,* args,** kwargs)文件“/Library/Python/2.7/site-packages/django/views/generic/base.py”in   调度     87.返回处理程序(request,* args,** kwargs)文件“/Library/Python/2.7/site-packages/django/views/generic/list.py”in   得到     152. context = self.get_context_data()文件“/Users/justahack/Documents/Python/tango_with_django_project/rango/views.py”   在get_context_data中     47. category = Category.objects.get(name = category_name)文件   “/Library/Python/2.7/site-packages/django/db/models/manager.py”获取     151.返回self.get_queryset()。get(* args,** kwargs)文件“/Library/Python/2.7/site-packages/django/db/models/query.py”获取     307. self.model._meta.object_name)

     

异常类型:/ rango / category / Perl / Exception值中的DoesNotExist:   类别匹配查询不存在。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:4)

问题是try / except块在方法之外,它无法捕获内部的异常。要修复它,请将try / except放入方法中:

def get_context_data(self, *args, **kwargs):
    context = super(CategoryView, self).get_context_data(*args, **kwargs)
    category_name = decode_url(self.kwargs['category_name_url'])

    # HERE
    try:
        category = Category.objects.get(name = category_name)
    except Category.DoesNotExist:
        raise Http404

    pages = Page.objects.filter(category = category)
    context['category'] = category
    context['pages'] = pages
    return context

此外,如果对象不存在,有一种更好的方法可以抛出404 - 使用get_object_or_404()快捷方式:

def get_context_data(self, *args, **kwargs):
    context = super(CategoryView, self).get_context_data(*args, **kwargs)
    category_name = decode_url(self.kwargs['category_name_url'])
    category = get_object_or_404(Category, name = category_name)
    pages = Page.objects.filter(category = category)
    context['category'] = category
    context['pages'] = pages
    return context