重定向到DjangoCMS中的自定义404 html页面

时间:2015-07-21 10:14:30

标签: django redirect django-templates django-cms

如果用户输入错误的路径,如何将用户重定向到我的自定义404.html页面?

views.py:

from django.shortcuts import render, render_to_response, redirect
from django.template import RequestContext

import threading

def url_redirect(request):
    return render_to_response('blog.html', RequestContext(request))

def post_redirect(request):
    return render_to_response('post.html', RequestContext(request))

def privacy_redirect(request):
    return render_to_response('privacy.html', RequestContext(request))

def terms_conditions_redirect(request):
    return render_to_response('terms.html', RequestContext(request))

def page_404(request):
    return render_to_response('404.html', RequestContext(request))

urls.py:

from __future__ import print_function
from cms.sitemaps import CMSSitemap
from django.conf.urls import *
from django.conf.urls.i18n import i18n_patterns
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from django.conf import settings
from django.conf.urls import patterns

admin.autodiscover()

urlpatterns = i18n_patterns('',
    url(r'^admin/', include(admin.site.urls)),
    url(r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': {'cmspages': CMSSitemap}}),
    url(r'^select2/', include('django_select2.urls')),

    url(r'^blog', "website.views.url_redirect", name="url-redirect"),
    url(r'^post', "website.views.post_redirect", name="post-redirect"),
    url(r'^privacy', "website.views.privacy_redirect", name="privacy-redirect"),
    url(r'^terms', "website.views.terms_conditions_redirect", name="terms_conditions-redirect"),
    url(r'^404', "website.views.page_404", name="page_404"),
    url(r'^', include('cms.urls')),
)

# This is only needed when using runserver.
if settings.DEBUG:
    urlpatterns = patterns('',
        url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
            {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
        ) + staticfiles_urlpatterns() + urlpatterns

我的TEMPLATE_DEBUG = True文件中也有DEBUG = Falsesettings.py。有什么帮助吗?

另外,你们可以告诉我views.py中的那些方法是否正常或是否可以更好地重写?

由于

1 个答案:

答案 0 :(得分:3)

在base.html附近添加404.html(主文件夹模板) 当出现错误404时,Django本身会占用您的404页面

在settings.py

DEBUG = False

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = ['yourweb.com']