当“调试”设置为“假”

时间:2019-06-22 09:12:50

标签: django debugging http-status-code-404

我最近尝试在我的网站上为我的404和500错误实现自定义视图。当debug设置为True时,它运行良好,即,两个自定义视图在调用时都运行良好。但是,只要将Debug设置为False,就只会引发错误500

我已经尝试通过创建URL来调用它们,handler404和handler500自定义视图都可以正常工作。

在该视图中,当它被错误调用时,它应该引发错误404:

def arret(request, id):
    """ Page that show an textuel """
    view = 'search/arret.html'
    arret = get_object_or_404(Arret, id=id)
    arret.compute_bgeref_id()
    query = request.GET.get('q', '')

    form_class =  DecisionForm()
    title = arret.highlight_words(query,input_text=arret.title)

    text = arret.highlight_words(query)
    arret_judges = arret.arret_judges.all()
    decision = arret.decision
    return render(request, view, {'title': title,'text': text, 'date':arret.date, 'tag_string': arret.tag_string, 'tags': arret.get_n_tags(), 'articles': arret.get_n_law_articles(n=15),
                                'bgeref_id': arret.bgeref_ids.all(),"form": form_class, 'id':id, 'query' : query, 'decision': decision,'arret_judges':arret_judges, 'ATF':arret.source=='ATF'
                                })

在这里您可以找到我的404自定义视图:

def handler404(request, template_name="colorlib-error-404-19/index.html"):
    response = render_to_response("colorlib-error-404-19/index.html")
    response.status_code = 404
    return response

在尝试查找不存在的Arret时会引发错误500。 这是在终端上写的

System check identified no issues (0 silenced).
June 22, 2019 - 08:55:31
Django version 2.0, using settings 'nora.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[22/Jun/2019 08:55:32] "GET /arret/100/?q=loi HTTP/1.1" 500 1435

编辑:添加设置文件

这是我的settings_file:

import os
from django.utils.translation import gettext_lazy as _
from requests_aws4auth import AWS4Auth
import elasticsearch

user = os.getenv('USER')
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY =  ##########################

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
if user == 'user':
    DEBUG = False
else:
    DEBUG = True

# ALLOWED_HOSTS

if user == 'user': # Checks if the settings is on the website
    ALLOWED_HOSTS = [ '.neuralen.ch', '.mstamenk.webfactional.com' ]
else :
    ALLOWED_HOSTS = ['*']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.sites',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'haystack',
    'search',
    'authUser',
    'debug_toolbar',
    'haystack_panel',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'debug_toolbar.middleware.DebugToolbarMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'nora.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, "templates"),],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                "django.template.context_processors.i18n",
            ],
        },
    },
]

#TEMPLATE_DIRS = ( failed attempt
#    os.path.join(BASE_DIR, 'templates'),
#)

WSGI_APPLICATION = 'nora.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases

if user == 'user': # Check if settings.py is on website server
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'NAME': 'nora_db',
            'USER': 'neuralen',
            'PASSWORD': #################,
            'HOST': '127.0.0.1',
            'PORT': '5432',
        },
        'nora_db_2': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'NAME': 'nora_db_2',
            'USER': 'neuralen',
            'PASSWORD': '################',
            'HOST': '127.0.0.1',
            'PORT': '5432',
        }

    }
else:                   # Otherwise, it's in local
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),


        },
        'nora_db_2': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'second_db.sqlite3'),
        },

    }

#DATABASE_ROUTERS = ['search.routers.SearchRouter']


# AWS 
AACCESS_KEY = ##########################
SECRET_KEY = ##########################
REGION = 'us-east-1'
AWSHOST = 'https://search-nora-y6ko4vsxcd4255tcs4gznzbaou.us-east-1.es.amazonaws.com'


awsauth = AWS4Auth(AACCESS_KEY,SECRET_KEY,REGION,'es')

# Haystack connection to elasticsearch.
#https://stackoverflow.com/questions/35090762/django-haystack-using-amazon-elasticsearch-hosting-with-iam-credentials?rq=1

HAYSTACK_CUSTOM_HIGHLIGHTER ="nora.utils.nora_Highlighter"

HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'haystack_es.backends.Elasticsearch5SearchEngine',
        #'URL': 'http://127.0.0.1:9200/',
        'URL': AWSHOST,
        'INDEX_NAME': 'nora',
        'INCLUDE_SPELLING' : True,
        'KWARGS': {
            'port': 443,
            'http_auth': awsauth,
            'use_ssl': True,
            'verify_certs': True,
            'connection_class': elasticsearch.RequestsHttpConnection,
        }
    },
}

if user == 'user':
    HAYSTACK_CONNECTIONS['default']['INDEX_NAME'] = 'nora-server'
else:
    HAYSTACK_CONNECTIONS['default']['INDEX_NAME'] = 'nora'


# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/

LANGUAGE_CODE = 'en-us'

#LANGUAGE_CODE = 'fr'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

gettext = lambda x: x

LANGUAGES = (
   ('en', _('English')),
   ('fr', _('French')),
   ('de', _('German')),
)

LOCALE_PATHS = (
    os.path.join(BASE_DIR, 'locale'),
)


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/

if user == 'user': # Check if on website
    STATIC_URL = 'https://neuralen.ch/django_nora_static/'
else:                  # Otherwise running in local
    STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static/"),
)
if user == 'user':
    STATIC_ROOT = '/home/user/webapps/django_nora_static/'
else:
    STATIC_ROOT = os.path.join(BASE_DIR, "static_root/")

# Authentification

LOGIN_URL = 'accounts/login'
LOGIN_REDIRECT_URL = '/'

#SMTP Email Serivce
#https://simpleisbetterthancomplex.com/tutorial/2016/06/13/how-to-send-email.html
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'testsite_app'
EMAIL_HOST_PASSWORD = '################'
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = 'TestSite Team <noreply@example.com>'
#EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'  # During development only

INTERNAL_IPS = [ '127.0.0.1']
DEBUG_TOOLBAR_PANELS = [
    'debug_toolbar.panels.versions.VersionsPanel',
    'debug_toolbar.panels.timer.TimerPanel',
    'debug_toolbar.panels.settings.SettingsPanel',
    'debug_toolbar.panels.headers.HeadersPanel',
    'debug_toolbar.panels.request.RequestPanel',
    'debug_toolbar.panels.sql.SQLPanel',
    'debug_toolbar.panels.staticfiles.StaticFilesPanel',
    'debug_toolbar.panels.templates.TemplatesPanel',
    'debug_toolbar.panels.cache.CachePanel',
    'debug_toolbar.panels.signals.SignalsPanel',
    'debug_toolbar.panels.logging.LoggingPanel',
    'debug_toolbar.panels.redirects.RedirectsPanel',
    'haystack_panel.panel.HaystackDebugPanel',
     ]

1 个答案:

答案 0 :(得分:0)

可能是您的设置文件没有ALLOWED_HOSTS

Django 1.5引入了出于安全原因而必需的allowed hosts setting

# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []

在此处添加主机,例如['www.example.com']['*']进行快速测试,但不要使用['*']进行生产

或者,可能是您尝试在不运行collectstatic的情况下访问某些静态文件。在大多数情况下,在视图中加载响应后,应该为404,但是如果您在代码中访问它们,则可能为500。