Programing

DEBUG = False로 설정하면 500 오류가 발생합니다

lottogame 2020. 3. 20. 08:13
반응형

DEBUG = False로 설정하면 500 오류가 발생합니다


를 변경하면 DEBUG = False내 사이트는 500을 생성하고 (wsgi & manage.py runserver 사용) Apache 오류 로그에 오류 정보가 없으며로 변경 debug하면 정상적으로 실행됩니다 True.

Django 1.5 및 Python 2.7.3을 사용하고 있습니다. 아파치 액세스 로그이며 아파치 오류 로그에 로그가 없습니다.

www.beta800.net:80 222.247.56.11 - - [28/Feb/2013:13:42:28 +0800] "GET / HTTP/1.1" 500 257 "-" "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.97 Safari/537.22"
www.beta800.net:80 222.247.56.11 - - [28/Feb/2013:13:42:28 +0800] "GET /favicon.ico HTTP/1.1" 500 257 "-" "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.97 Safari/537.22"
www.beta800.net:80 222.247.56.11 - - [28/Feb/2013:13:42:28 +0800] "GET /favicon.ico HTTP/1.1" 500 257 "-" "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.97 Safari/537.22"

내 설정 파일은 다음과 같습니다.

import os.path    
DEBUG = False 
#TEMPLATE_DEBUG = DEBUG

HERE = os.path.dirname(__file__)
ADMINS = (
    ('admin', 'xyzadmin@qq.com'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'zdm',                      # Or path to database file if using sqlite3.
        'USER': 'root',                      # Not used with sqlite3.
        'PASSWORD': 'passwd',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/Chicago'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True

# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
#STATIC_ROOT = os.path.join(HERE, 'static').replace('\\','/')

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
#STATIC_ROOT = os.path.join(HERE, 'static').replace('\\','/')
S= os.path.join(HERE, 'static').replace('\\','/')

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    '/home/zdm/static',
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY = '9a7!^gp8ojyk-^^d@*whuw!0rml+r+uaie4ur$(do9zz_6!hy0'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#     'django.template.loaders.eggs.Loader',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'zdm.urls'

# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'zdm.wsgi.application'

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    '/home/zdm/templates',
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
    'zdm',
    'portal',
    'admin',
    'tagging',
)

Django 1.5에는 보안상의 이유로 허용되는 호스트 설정도입되었습니다 . Django 1.5로 만든 설정 파일에는 다음과 같은 새로운 섹션이 추가되었습니다.

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

여기에 ['www.beta800.net']또는 ['*']빠른 테스트를 위해 호스트를 추가 하지만 ['*']프로덕션 에는 사용하지 마십시오 .


나는이 말을 알고하지만 난 내 오류 500에 대한 검색 여기 결국 DEBUG=False, 내 경우는 것으로 판명 않았다 ALLOWED_HOSTS그러나 나는 사용했다 os.environ.get('variable')당신이 할 수있는, 내가 로깅을 활성화 할 때까지 나는이 통지를하지 않았다 호스트를 채울 다음과 같이 파일에 모든 오류를 기록하면 다음과 같은 경우에도 기록됩니다 DEBUG=False.

# settings.py
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
            'datefmt' : "%d/%b/%Y %H:%M:%S"
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'mysite.log',
            'formatter': 'verbose'
        },
    },
    'loggers': {
        'django': {
            'handlers':['file'],
            'propagate': True,
            'level':'DEBUG',
        },
        'MYAPP': {
            'handlers': ['file'],
            'level': 'DEBUG',
        },
    }
}

제 경우에는 타사 앱 문서를 읽으면 저를 구했습니다.

그 범인? django_compressor

나는했다

{% load compress %}
{% compress css %}
 ... css files linked here ..
{% endcompress %}

DEBUG = True 이 문제를 해결하려면 설정에 줄이 필요했습니다.

COMPRESS_ENABLED = os.environ.get('COMPRESS_ENABLED', False)

Django 2.0에서 최근에 같은 문제가 발생했습니다. 설정하여 문제를 파악할 수있었습니다 DEBUG_PROPAGATE_EXCEPTIONS = True. 여기를 참조하십시오 https://docs.djangoproject.com/en/2.0/ref/settings/#debug-propagate-exceptions

제 경우에는 오류가 ValueError: Missing staticfiles manifest entry for 'admin/css/base.css'입니다. 로컬로 실행하여 문제를 해결했습니다 python manage.py collectstatic.


Django 1.5에서 DEBUG = False 인 경우 포트 번호없이 도메인을 추가하여 ALLOWED_HOSTS를 구성하십시오. 예:

ALLOWED_HOSTS = ['localhost']

또한 모든 곳에서 URL을 확인해야합니다. DEBUG로 설정 하면 False후행 /없는 모든 URL 은 사용자와 달리 버그로 취급됩니다. DEBUG = True이 경우 Django /는 누락 된 모든 위치에 추가 합니다. 즉, 모든 링크가 어디에서나 슬래시로 끝나는 지 확인하십시오.


나는 모두에게 재미있는 이야기가 있습니다. 이 페이지에 도달 한 후 나는 "유레카! 나는 구원을 받았다. 그것은 나의 문제 여야한다"고 말했다. 그래서 필요한 ALLOWED_HOSTS목록을 setting.py에 삽입했습니다 ... 아무것도 없습니다. 이전 500 오류와 동일합니다. 그리고 아닙니다. 404.html 파일이 부족하지 않았습니다.

그래서 2 일 동안 나는 정적 파일을 제공하는 것과 관련이있는 것과 같은 야생 이론으로 나 자신을 바꿨습니다 (나는 멍청한 놈이며 멍청한 사람들은 그들이하는 일을 모른다는 것을 이해합니다).

그래서 무엇입니까? 이제 우리는 유용한 팁을 얻는 것이 중재자 Mr. 내 개발 Django는 버전 1.5.something, 내 프로덕션 서버 버전은 1.5.something + 1 ... 또는 플러스 2입니다. 그리고 ALLOWED_HOSTS데스크톱 버전의 settings.py 에 hwjp가 요청한 것 ( "settings.py의 기본값, 아마도 설명이있는 설명"이 없음)에 데스크톱 버전을 추가 한 후 프로덕션 서버에서 동일한 작업을 수행했습니다. 적절한 도메인.

그러나 최신 버전의 Django가있는 프로덕션 서버에는 settings.py에 기본값이 설명 설명과 함께 있음을 알지 못했습니다. 모니터에서 보이지 않게 입장을 한 곳은 아래에있었습니다. 물론 목록은 비어있었습니다. 따라서 시간 낭비.


그만한 가치가 있기 때문에 DEBUG = False일부 페이지에서만 500을 얻었습니다 . pdb로 예외를 추적하면 누락 된 자산이 발견되었습니다 ( {% static ... %}템플릿 태그가 500의 범인이라고 생각합니다 .


내가 할 때 같은 문제에 직면했다 DEBUG = FALSE. 위의 답변과 다른 게시물에 흩어져있는 통합 솔루션이 있습니다.

기본적으로 settings.py에는가 있습니다 ALLOWED_HOSTS = []. ALLOWED_HOSTS오류를 제거하기 위해 시나리오별로 가치 를 변경해야 할 수있는 사항은 다음과 같습니다 .

1 : 도메인 이름 :

ALLOWED_HOSTS = ['www.example.com'] # Your domain name here

2 : 아직 도메인 이름이없는 경우 배포 된 서버 IP (내 경우에는 매력처럼 작동 함) :

ALLOWED_HOSTS = ['123.123.198.123'] # Enter your IP here

3 : 로컬 서버에서 테스트하는 경우 settings.py또는 다음 settings_local.py과 같이 편집 할 수 있습니다 .

ALLOWED_HOSTS = ['localhost', '127.0.0.1']

4 : ALLOWED_HOSTS값으로 '*'를 제공 할 수 있지만 보안상의 이유로 프로덕션 환경에서는 권장되지 않습니다 .

ALLOWED_HOSTS = ['*'] # Not recommended in production environment

또한 내 블로그 에 참조 할 수 있는 자세한 솔루션을 게시했습니다 .


주요 답변 보완 개발과 프로덕션 사이를 전환 할 때
ALLOWED_HOSTS 및 DEBUG 전역 상수를 변경하는 것은 성가신 일입니다 settings.py. 이 코드를 사용하여 이러한 설정을 자동으로 설정하고 있습니다.

import socket

if socket.gethostname() == "server_name":
    DEBUG = False
    ALLOWED_HOSTS = [".your_domain_name.com",]
    ...
else:
    DEBUG = True
    ALLOWED_HOSTS = ["localhost", "127.0.0.1",]
    ...

macOS를 사용하면보다 일반적인 코드를 작성할 수 있습니다.

if socket.gethostname().endswith(".local"): # True in your local computer
    DEBUG = True
    ALLOWED_HOSTS = ["localhost", "127.0.0.1",]
else:
    ...

ALLOWED_HOSTS가 유일한 문제는 아닙니다. 저는 404.html을 만들어 템플릿의 기본 수준 (앱 수준이 아님)에 넣어야했습니다. 또한 404보기를 만들고 404handler URL을 추가 할 수는 있지만 그렇게 생각합니다. 선택 과목. 404.html 수정

mainproject.urls에서

handler404 = 'app.views.custom_404'

app.views에서

def custom_404(request):
    return render(request, '404.html', {}, status=404)

그런 다음 templates / 404.html 템플릿을 만듭니다.

찾을 수없는 다른 S / O 게시물에서 이것을 얻었습니다.

편집하다

또한 화이트 노이즈가있는 자산을 제공 할 때 500 개의 오류가 발생합니다. 내 인생에서 오류를 알 수 없었습니다. 오류는 whitenoise의 ValueError이기도합니다. 찾을 수없는 자산을 찾을 수 없으며 현재 기본 장고 서비스와 함께 가야했습니다.


필자는이 문제에 대해 더 많이 검색하고 테스트했으며 settings.py에 지정된 정적 파일 디렉토리가 원인 일 수 있음을 깨달았습니다. 그래서이 명령을 실행해야합니다

python manage.py collectstatic

settings.py에서 코드는 다음과 같아야합니다.

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

나는 이것이 매우 오래된 질문이라는 것을 알고 있지만 다른 도움을 줄 수 있습니다. DEBUG = False를 설정 한 후 500 오류가 발생하면 명령 줄에서 항상 manage.py runserver를 실행하여 웹 오류 로그에 표시되지 않는 오류를 확인할 수 있습니다.


http 서버 설정 일 수도 있다고 생각합니다. 광산은 여전히 ​​망가졌고 내내 ALLOWED_HOSTS을했습니다. 로컬로 액세스 할 수 있지만 (gunicorn 사용) DEBUG = False 인 경우 도메인 이름을 통해 액세스 할 수 없습니다. 도메인 이름을 사용하려고하면 오류가 발생하므로 nginx 관련 문제로 생각합니다.

다음은 nginx의 conf 파일입니다.

server {
    listen   80;
    server_name localhost myproject.ca www.myproject.ca;
    root /var/web/myproject/deli_cms;

    # serve directly - analogous for static/staticfiles
    location /media/ {
        # if asset versioning is used
        if ($query_string) {
            expires max;
        }
    }
    location /admin/media/ {
        # this changes depending on your python version
        root /var/web/myproject/lib/python2.6/site-packages/django/contrib;
    }
    location /static/ {
    alias /var/web/myproject/deli_cms/static_root/;
    }

    location / {
        proxy_pass_header Server;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Scheme $scheme;
        proxy_connect_timeout 10;
        proxy_read_timeout 10;
        proxy_pass http://localhost:8000/;
    }
    # what to serve if upstream is not available or crashes
    error_page 500 502 503 504 /media/50x.html;
}

비슷한 문제가 있습니다. 제 경우에는 body 태그 안에 주석 처리 된 스크립트가있어서 발생했습니다.

<!--<script>  </script>-->

나는이 문제에 부딪쳤다. static더 이상 존재하지 않는 파일 인 템플릿 태그를 사용하여 템플릿 에 포함하고있는 것으로 나타났습니다 . 로그를 보면 문제가 있음을 알 수 있습니다.

나는 이것이 이런 종류의 오류에 대한 많은 가능한 이유 중 하나 일 것이라고 생각합니다.

이야기의 도덕 : 항상 오류를 기록하고 항상 로그를 확인하십시오.


@squarebear 덕분에 로그 파일에서 오류가 발견되었습니다 ValueError: The file 'myapp/styles.css' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage ...>.

내 장고 앱에 몇 가지 문제가있었습니다.
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'heroku의 문서에서 찾은 제거했습니다 .

또한 (덕분에 별도의 디렉토리를 추가했다 다른 SO 응답 ) static로 장고 응용 프로그램의 루트에 myapp/static나는 그것을 사용하지 않을에도 불구하고. 그런 다음 python manage.py collectstatic서버를 실행하기 전에 명령 을 실행하면 문제가 해결되었습니다. 마침내, 그것은 잘 작동하기 시작했습니다.


2019 년 중반에 장고로 몇 년 동안 개발 한 후이 오류에 직면했습니다. 밤새도록 당황했다! 호스트를 허용하지 않았고 (400을 던져야 함) 다른 모든 체크 아웃은 마침내 일부 오류 로깅을 수행하여 누락되거나 엉망이 된 정적 파일 (정적 후)이 설정과 관련이 있음을 발견했습니다. 간결하게 말하면, 혼란에 빠진 사람들은 화이트 노이즈 또는 CACHE (manfest 정적 파일)와 함께 장고 정적 파일 백엔드를 사용하고 있습니다.

  1. 화이트 노이즈 백엔드에서와 같이 모든 것을 설정했는지 확인하십시오 (django 백엔드는 그럼에도 불구하고 읽습니다) http://whitenoise.evans.io/en/stable/django.html

  2. 오류 코드 500이 계속 표시되면 설정에 유의하십시오 .STATICFILES_STORAGE.

압축으로 whitenoise 백엔드의 경우로 설정하십시오.

STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'

또는 (장고 기본값으로 두십시오)

STATICFILES_STORAGE = django.contrib.staticfiles.storage.StaticFilesStorage

대체로, 문제는이 화이트 노이즈 캐시 + 압축 백엔드->

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

또는 django의 자체 캐싱 백엔드->

STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'

... CSS는 collectstatic / backend 캐싱 중에 혼합 될 수있는 다른 소스를 참조했기 때문에 꽤 잘 작동했습니다. 이 문제는 http://whitenoise.evans.io/en/stable/django.html#storage-troubleshoot 에서도 잠재적으로 강조 표시됩니다 .


나는 500의 형태로 debug = False를 얻기 시작했다

django.urls.exceptions.NoReverseMatch: Reverse for 'home' not found.
or...
django.urls.exceptions.NoReverseMatch: Reverse for 'about' not found.

상승 할 때 django.core.exceptions.ValidationError을 대신 양육의 rest_framework.serializers.ValidationError를

공평하게, 그것은 이미 500을 제기했지만 debug = False 인 ValidationError로 NoReverseMatch로 변경되었습니다.


나는 이것이 오래된 질문이라는 것을 알고 있지만 DEBUG = False 일 때 500 오류가 발생했습니다. 몇 시간 후, 나는 base.html의 일부 링크를 슬래시로 끝내는 것을 잊었다는 것을 깨달았습니다.


이것은 오래되었고 내 문제는 문제와 관련이 있었지만 OP와는 관련이 없지만 위의 시도는 아무 소용이없는 사람을위한 것입니다.

Django의 수정 된 버전에서 DEBUG가 꺼져있을 때만 실행되는 CSS 및 JS 파일을 최소화하도록 설정했습니다. 내 서버에 CSS 축소 기가 설치되어 있지 않아 오류가 발생했습니다. Django-Mako-Plus를 사용하는 경우 이것이 문제 일 수 있습니다.


한 가지주의해야 할 점은 배열에 None이 있으면 이후에 허용되는 모든 호스트가 무시됩니다.

ALLOWED_HOSTS = [
    "localhost",
    None,
    'example.com', # First DNS alias (set up in the app)
    #'www.example.com', # Second DNS alias (set up in the app)
]

Django version 1.8.4


파티에 조금 늦었고 물론 다른 문제가있을 수는 있지만 비슷한 문제가 발생하여 HTML 비고 안에 {% %} 개의 특수 문자가있는 것으로 나타났습니다 ...

<!-- <img src="{% static "my_app/myexample.jpg" %}" alt="My image"/> -->

debug = false에서 500 오류가 발생했지만 debug = true에서 작동하는 하나의보기가 있습니다. 이런 종류의 물건을 가지고 있고 허용 호스트에 문제가없는 사람에게는 잘못된 위치를 가리키는 템플릿의 정적 태그를 업데이트하여 내 견해를 수정했습니다.

따라서 링크와 태그를 확인하는 것은 사용 된 모든 템플릿에서 기밀 한 것입니다. 어쩌면 디버그에서 그물을 통해 미끄러지지 만 생산에는 오류가 발생할 수 있습니다.


DEBUG = False 일 때 500 오류의 또 다른 원인을 찾았습니다. Django compressor유틸리티를 사용하고 프론트 엔드 엔지니어 가 Django 템플릿 블록 안에 있는 글꼴 파일에 대한 참조를 추가했습니다 compress css. 이처럼 :

{% compress css %}
    <link href="{% static "css/bootstrap.css" %}" rel="stylesheet">
    <link href="{% static "css/bootstrap-spinedit.css" %}" rel="stylesheet">
    <link href="{% static "djangular/css/styles.css" %}" rel="stylesheet">
    <link href="{% static "fonts/fontawesome-webfont.ttf" %}" rel="stylesheet">
{% endcompress %}

해결책은 링크를 ttf파일 아래의 endcompress아래 로 옮기는 것이 었습니다 .


나는 이와 비슷한 문제를 겪었고 누군가도 같은 경험을 할 수 있기 때문에 어떻게 내 문제를 해결했는지보고 할 것입니다.

제 경우에는 서버가 홈페이지에서 일부 정적 파일을 찾지 못해 오류가 발생했습니다.

따라서 오류 index가 다른 페이지 에서만 발생 하거나 다른 페이지 에서 발생하는지 확인 하십시오. 인덱스에서만 문제가 발생하면 정적 파일을 확인해야합니다. Chrome 미리보기 콘솔을 열고 오류를 확인하는 것이 좋습니다.

필자의 경우 서버에서 favicon.ico두 개의 다른 CSS를 찾을 수 없습니다 .

이 문제를 해결하기 위해 통과 python manage.py collectstatic했고 효과가있었습니다.


모든 호스트를 허용하려는 경우. ALLOWED_HOSTS = [ '*'] 대신 ALLOWED_HOSTS = [ '*',]를 사용하십시오.

참고 URL : https://stackoverflow.com/questions/15128135/setting-debug-false-causes-500-error

반응형