Почему я не могу установить DEBUG = False в моем приложении django на dreamhost без ошибки? - PullRequest
0 голосов
/ 07 сентября 2010

Я успешно запускаю свою страницу на основе Django в течение некоторого времени. Теперь я решил выключить режим отладки и реализовать хороший файл 404.html. Проблема в том, что как только я меняю DEBUG на «False» в моем файле settings.py, я сразу же получаю ошибки сервера, которые мне не понятны, независимо от того, какую страницу я пытаюсь посетить. Существующие страницы или несуществующие страницы (которые должны показать мой 404.html) все выдают ошибки.

Я использую Django на Dreamhost, используя пассажира. Чтобы начать получать полезные сообщения об ошибках, я следовал инструкциям на wiki dreamhosts и настроил свой файл passenger_wsgi.py в соответствии с этими инструкциями , используя вставку модуля. Это мой passenger_wsgi.py:

import sys, os
INTERP = "/home/bhogberg/bin/python"
if sys.executable != INTERP: os.execl(INTERP, INTERP, *sys.argv)
cwd = os.getcwd()
myapp_directory = cwd + '/homepage'
sys.stdout = sys.stderr
sys.path.insert(0,myapp_directory)
sys.path.append(os.getcwd())
os.environ['DJANGO_SETTINGS_MODULE'] = "homepage.settings"
import django.core.handlers.wsgi
from paste.exceptions.errormiddleware import ErrorMiddleware
application = django.core.handlers.wsgi.WSGIHandler()
# To cut django out of the loop, comment the above application = ... line ,
# and remove "test" from the below function definition.
def testapplication(environ, start_response):
    status = '200 OK'
    output = 'Hello World! Running Python version ' + sys.version + '\n\n'
    response_headers = [('Content-type', 'text/plain'),
                        ('Content-Length', str(len(output)))]
    #to test paste's error catching prowess, uncomment the following line
    #while this function is the "application"
    #raise("error")
    start_response(status, response_headers)
    return [output]
application = ErrorMiddleware(application, debug=True)

Я также пытался изменить отладку последней строки на False, в этом случае я тоже получаю ошибки.

Все работает нормально, пока у меня DEBUG = True в settings.py

Это ошибки, которые я получаю, когда просто включаю Debug = False (сообщается через вставку, а не сообщения об ошибках django):

Server Error

Module paste.exceptions.errormiddleware:144 in __call__
<<              __traceback_supplement__ = Supplement, self, environ
                sr_checker = ResponseStartChecker(start_response)
                app_iter = self.application(environ, sr_checker)
                return self.make_catching_iter(app_iter, environ, sr_checker)
            except:
Module django.core.handlers.wsgi:241 in __call__
<<                  response = http.HttpResponseBadRequest()
                else:
                    response = self.get_response(request)

                    # Apply response middleware
Module django.core.handlers.base:142 in get_response
<<                  exc_info = sys.exc_info()
                    receivers = signals.got_request_exception.send(sender=self.__class__, request=request)
                    return self.handle_uncaught_exception(request, resolver, exc_info)
            finally:
                # Reset URLconf for this thread on the way out for complete
Module django.core.handlers.base:177 in handle_uncaught_exception
<<          mail_admins(subject, message, fail_silently=True)
            # If Http500 handler is not installed, re-raise last exception
            if resolver.urlconf_module is None:
                raise exc_info[1], None, exc_info[2]
            # Return an HttpResponse that displays a friendly error message.

Module django.core.urlresolvers:238 in _get_urlconf_module
<<              return self._urlconf_module
            except AttributeError:
                self._urlconf_module = import_module(self.urlconf_name)
                return self._urlconf_module
        urlconf_module = property(_get_urlconf_module)
Module django.utils.importlib:35 in import_module
<<              level += 1
            name = _resolve_name(name[level:], package, level)
        __import__(name)
        return sys.modules[name]
Module ?:3 in <module>
<<  from django.conf.urls.defaults import *
    from django.contrib import admin
    admin.autodiscover()

    import os.path
Module django.contrib.admin:24 in autodiscover
<<          try:
                before_import_registry = copy.copy(site._registry)
                import_module('%s.admin' % app)
            except:
                # Reset the model registry to the state before the last import as

Module django.utils.importlib:35 in import_module
<<              level += 1
            name = _resolve_name(name[level:], package, level)
        __import__(name)
        return sys.modules[name]
Module ?:6 in <module>
<<  

    admin.site.register(Page, PageAdmin)
Module django.contrib.admin.sites:93 in register
<<  
                # Instantiate the admin class to save in the registry
                self._registry[model] = admin_class(model, self)

        def unregister(self, model_or_iterable):
Module feincms.module.page.models:634 in __init__
<<  
        def __init__(self, *args, **kwargs):
            if len(Page._feincms_templates) > 4:
                del(self.radio_fields['template_key'])
AttributeError: type object 'Page' has no attribute '_feincms_templates'

1 Ответ

1 голос
/ 17 августа 2011

На тот случай, если у кого-то еще возникла эта проблема, это потому, что Dreamhost использует слегка устаревшую версию Django 1.2 с ошибкой:

https://code.djangoproject.com/ticket/15343

Решение состоит в том, чтобы изменить строку импорта для явного включения handler404 и handler500, после чего вы можете настроить свой корневой urlConf. Я показал быстрый пример ниже:

from django.conf.urls.defaults import patterns, include, url, handler404, handler500
from django.conf import settings
from django.contrib import admin

admin.autodiscover()

urlpatterns = patterns('',
  url('handler404', 'django.views.defaults.page_not_found'),
  url('handler500', 'django.views.defaults.server_error'),
  url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATICFILES_DIRS[0]}),
  url(r'^$', include('home.urls')),
  url(r'^about/', include('about.urls')),
  url(r'^contact/', include('contactsubmission.urls')),
  url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
  url(r'^admin/', include(admin.site.urls)),
)
...