【问题标题】:Writing custom view for 404 render 500 Error page为 404 渲染 500 错误页面编写自定义视图
【发布时间】:2014-08-07 08:42:09
【问题描述】:

我想编写一个自定义视图来呈现我的 404。所以我这样定义它:

class PageNotFoundView(IndexView):
    template_name = 'blogengine/404.html'

    def get_queryset(self):
        return Post.objects.none

    def get_context_data(self):
        return self.get_context_categories()

它派生的IndexView是

class IndexView(ListView):
    def get_context_categories(self):
        context = super(IndexView, self).get_context_data(**self.kwargs)
        context['categories'] = Category.objects.all()
        return context

因为我想要所有页面中的所有类别。

并在我的主 urlconf 中像这样设置 urlconf

from django.conf.urls import patterns, include, url
from django.contrib import admin
from blogengine.views import PageNotFoundView

admin.autodiscover()

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    url(r'', include('blogengine.urls')),
)

handler404 = PageNotFoundView.as_view()

在 settings.py 中我放置了我需要的主机:

DEBUG = False

TEMPLATE_DEBUG = False

ALLOWED_HOSTS = ['my.customHost.com', 'localhost', '127.0.0.1',]

但是当我部署它时,当我尝试错误的 URL 时出现 500 内部错误。

有什么想法吗?

【问题讨论】:

    标签: django python-3.x http-status-code-404


    【解决方案1】:

    不需要所有的东西,小心你的定义,它们需要和原来的一样。

    class PageNotFoundView(TemplateView):
        template_name = 'blogengine/404.html'
    
        def get_context_data(self, **kwargs):
            context = super(PageNotFoundView, self).get_context_data(**kwargs)
            try:
                context['categories'] = Category.objects.all()
            except:
                pass
            return context
    

    【讨论】:

    • 那么回溯是什么?
    • 你的观点给了我这个:回溯(最近一次调用最后):文件“/usr/lib64/python3.4/wsgiref/handlers.py”,第 138 行,运行 self.finish_response()文件“/usr/lib64/python3.4/wsgiref/handlers.py”,第 179 行,finish_response 中 self.result 中的数据:文件“/home/juanwolf/Documents/tools/virtualenvs/python3/lib/python3.4 /site-packages/django/template/response.py", line 118, in iter raise ContentNotRenderedError('响应内容必须是' django.template.response.ContentNotRenderedError: 响应内容必须被渲染在它可以被迭代之前。
    • 必须为自定义 404 视图手动呈现 TemplateView 实例。试试response = TemplateResponse(request, self.template_name, context); response.render(); return response
    • @JuanWolf 你能解决这个问题吗?我也有同样的问题。
    • @akshay 是的。我将基于类的视图更改为一个函数。在您项目的主要 urls.py 中,我使用了:handler404 = "myapp.views.page_not_found_view"。抱歉,BTW 回复晚了
    猜你喜欢
    • 2013-07-13
    • 1970-01-01
    • 2013-02-04
    • 2011-01-23
    • 1970-01-01
    • 2015-08-26
    • 1970-01-01
    • 2016-04-25
    • 2013-09-16
    相关资源
    最近更新 更多