Dango应用未正确部署在Heroku上:DEBUG = False时服务器错误500,DEBUG = True

时间:2019-01-15 01:19:16

标签: python django heroku server

在本地,我的Django应用完美运行。

我能够在Heroku上部署该应用程序,但是当DEBUG = False时在setting.py中运行,则GET pypoll.herokuapp.com/polls会导致“服务器错误(500)”。 Heroku日志也只显示状态= 500。

2019-01-14T20:23:33.934156+00:00 heroku[web.1]: State changed from up to starting
2019-01-14T20:23:35.192270+00:00 heroku[web.1]: Process exited with status 0
2019-01-14T20:23:40.447711+00:00 heroku[web.1]: Starting process with command `gunicorn mysite.wsgi --log-file -`
2019-01-14T20:23:44.348545+00:00 heroku[web.1]: State changed from starting to up
2019-01-14T20:23:44.216211+00:00 app[web.1]: [2019-01-14 20:23:44 +0000] [4] [INFO] Starting gunicorn 19.9.0
2019-01-14T20:23:44.221560+00:00 app[web.1]: [2019-01-14 20:23:44 +0000] [4] [INFO] Listening at: http://0.0.0.0:23263 (4)
2019-01-14T20:23:44.221733+00:00 app[web.1]: [2019-01-14 20:23:44 +0000] [4] [INFO] Using worker: sync
2019-01-14T20:23:44.232516+00:00 app[web.1]: [2019-01-14 20:23:44 +0000] [10] [INFO] Booting worker with pid: 10
2019-01-14T20:23:44.301182+00:00 app[web.1]: [2019-01-14 20:23:44 +0000] [11] [INFO] Booting worker with pid: 11
2019-01-14T20:23:46.601813+00:00 app[web.1]: /app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>.
2019-01-14T20:23:46.601856+00:00 app[web.1]: """)
2019-01-14T20:23:46.729941+00:00 app[web.1]: /app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>.
2019-01-14T20:23:46.729944+00:00 app[web.1]: """)
2019-01-14T20:31:23.859217+00:00 heroku[router]: at=info method=GET path="/" host=pypoll.herokuapp.com request_id=0c2da020-6e94-4feb-ac0a-23ed191041de fwd="47.183.12.128" dyno=web.1 connect=1ms service=178ms status=404 bytes=258 protocol=https
2019-01-14T20:31:23.858394+00:00 app[web.1]: 10.41.219.86 - - [14/Jan/2019:14:31:23 -0600] "GET / HTTP/1.1" 404 77 "https://dashboard.heroku.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
2019-01-14T20:31:30.389836+00:00 app[web.1]: 10.41.219.86 - - [14/Jan/2019:14:31:30 -0600] "GET /polls/ HTTP/1.1" 500 27 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
2019-01-14T20:31:30.390638+00:00 heroku[router]: at=info method=GET path="/polls/" host=pypoll.herokuapp.com request_id=02fb8930-785e-46d5-9314-fccd75d6691d fwd="47.183.12.128" dyno=web.1 connect=1ms service=571ms status=500 bytes=234 protocol=https

当我设置DEBUG = True以获取更多信息时,GET pypoll.herokuapp.com/polls会加载一个页面,显示“没有可用的民意调查”。来自我的root / polls / templates / poll / index.html。同样奇怪的是,在pypoll.herokuapp.com/admin/login/?next=/admin/,我的凭据无法登录。

2019-01-14T20:57:46.759168+00:00 heroku[web.1]: Stopping all processes with SIGTERM
2019-01-14T20:57:46.781544+00:00 app[web.1]: [2019-01-14 20:57:46 +0000] [4] [INFO] Handling signal: term
2019-01-14T20:57:46.781601+00:00 app[web.1]: [2019-01-14 14:57:46 -0600] [10] [INFO] Worker exiting (pid: 10)
2019-01-14T20:57:46.782299+00:00 app[web.1]: [2019-01-14 14:57:46 -0600] [11] [INFO] Worker exiting (pid: 11)
2019-01-14T20:57:46.984138+00:00 app[web.1]: [2019-01-14 20:57:46 +0000] [4] [INFO] Shutting down: Master
2019-01-14T20:57:47.139905+00:00 heroku[web.1]: Process exited with status 0
2019-01-14T20:57:51.345486+00:00 heroku[web.1]: Starting process with command `gunicorn mysite.wsgi --log-file -`
2019-01-14T20:57:54.369197+00:00 app[web.1]: [2019-01-14 20:57:54 +0000] [4] [INFO] Starting gunicorn 19.9.0
2019-01-14T20:57:54.369795+00:00 app[web.1]: [2019-01-14 20:57:54 +0000] [4] [INFO] Listening at: http://0.0.0.0:27705 (4)
2019-01-14T20:57:54.369940+00:00 app[web.1]: [2019-01-14 20:57:54 +0000] [4] [INFO] Using worker: sync
2019-01-14T20:57:54.373762+00:00 app[web.1]: [2019-01-14 20:57:54 +0000] [10] [INFO] Booting worker with pid: 10
2019-01-14T20:57:54.423266+00:00 app[web.1]: [2019-01-14 20:57:54 +0000] [11] [INFO] Booting worker with pid: 11
2019-01-14T20:57:55.102774+00:00 heroku[web.1]: State changed from starting to up
2019-01-14T20:57:54.933132+00:00 app[web.1]: /app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>.
2019-01-14T20:57:54.933169+00:00 app[web.1]: """)
2019-01-14T20:57:54.936230+00:00 app[web.1]: /app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>.
2019-01-14T20:57:54.936233+00:00 app[web.1]: """)
2019-01-14T20:57:54.000000+00:00 app[api]: Build succeeded
2019-01-14T20:58:03.435819+00:00 heroku[router]: at=info method=GET path="/" host=pypoll.herokuapp.com request_id=07c2b7a0-d1a9-4839-b864-b4144626fd74 fwd="47.183.12.128" dyno=web.1 connect=1ms service=33ms status=404 bytes=2217 protocol=https
2019-01-14T20:58:03.435316+00:00 app[web.1]: Not Found: /
2019-01-14T20:58:03.436524+00:00 app[web.1]: 10.47.171.78 - - [14/Jan/2019:14:58:03 -0600] "GET / HTTP/1.1" 404 2034 "https://dashboard.heroku.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
2019-01-14T20:58:13.401080+00:00 heroku[router]: at=info method=GET path="/polls/" host=pypoll.herokuapp.com request_id=0fde1142-b333-45ca-b3c3-e993186e7292 fwd="47.183.12.128" dyno=web.1 connect=1ms service=126ms status=200 bytes=421 protocol=https
2019-01-14T20:58:13.401609+00:00 app[web.1]: 10.47.171.78 - - [14/Jan/2019:14:58:13 -0600] "GET /polls/ HTTP/1.1" 200 231 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"

我是Django和Heroku的新手,但是我已经进行了广泛的搜索以寻求解决方案,但没有成功。 我不认为这是一个静态文件问题,但是我对Heroku部署所做的sets.py更改一定不正确。

项目目录如下:

mysite/
    manage.py
    mysite/
        __init__.py
        settings.py
        urls.py
        wsgi.py
    polls/
        __init__.py
        admin.py
        migrations/
            __init__.py
            0001_initial.py
        models.py
        static/
            polls/
                images/
                    background.gif
                style.css
        templates/
            polls/
                detail.html
                index.html
                results.html
        tests.py
        urls.py
        views.py
    templates/
        admin/
            base_site.html

mysite / setting.py

import os
import django_heroku
import dj_database_url

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

DEBUG = True

TEMPLATE_DEBUG = False

ALLOWED_HOSTS = [
    '*',
    '.***.com',
    '.herokuapp.com',
    'localhost',
    '127.0.0.1',
    'pypoll.herokuapp.com',
]

INSTALLED_APPS = [
    'polls.apps.PollsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

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

ROOT_URLCONF = 'mysite.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',
            ],
        },
    },
]

WSGI_APPLICATION = 'mysite.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'HOST': '',
        'PORT': '',
        'NAME': 'trupoll',
        'USER': 'root',
        'PASSWORD': '***********',
        'CONN_MAX_AGE': 500,
    }
}

# Heroku: Update database configuration from $DATABASE_URL.

# DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True)
# db_from_env = dj_database_url.config(conn_max_age=500)
# DATABASES['default'].update(db_from_env)

django_heroku.settings(locals())

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
# STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
STATICFILES_FINDERS = [
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
# STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

mysite / urls.py

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
    # path('/', include('polls.urls')),
]

polls / models.py

import datetime

from django.db import models
from django.utils import timezone

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text

    def was_published_recently(self):
        now = timezone.now()
        return now - datetime.timedelta(days=1) <= self.pub_date <= now

    was_published_recently.admin_order_field = 'pub_date'
    was_published_recently.boolean = True
    was_published_recently.short_description = 'Published recently?'

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

polls / urls.py

from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('<int:pk>/', views.DetailView.as_view(), name='detail'),
    path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
    path('<int:question_id>/vote/', views.vote, name='vote'),
]

polls / views.py

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views import generic
from django.utils import timezone
from .models import Choice, Question

class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_question_list'

    def get_queryset(self):
        """ Return last five questions """
        return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5]

# <img src="{% static "polls/images/mphg3.png" %}" alt="polls background">

class DetailView(generic.DetailView):
    model = Question
    template_name = 'polls/detail.html'

    def get_queryset(self):
        """ Excludes any questions that aren't published yet """
        return Question.objects.filter(pub_date__lte=timezone.now())

polls / templates / polls / index.html

<body>
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}">
{% if latest_question_list %}
    <ul>
    {% for question in latest_question_list %}
        <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}
</body>

templates / admin / base_site.html

{% block branding %}
<h1 id="site-name"><a href="{% url 'admin:index' %}">PyPoll Administration</a></h1>
{% endblock %}

2 个答案:

答案 0 :(得分:0)

当您点击/polls/路由时,会收到内部服务器错误。这行:

return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5]
polls/urls.py中的

错误,因为您要查询[:5]中长度为0的查询集的一部分。您的网站上没有民意调查。

答案 1 :(得分:0)

您似乎需要创建一个数据库。对您来说很幸运Heroku有一个简单的方法。将以下内容替换为您选择的提供者给您的信誉。我相信如果您想要MySql CLEARDB将是一个不错的选择。祝您好运,我希望这会有所帮助。

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.mysql',
    'HOST': '',
    'PORT': '',
    'NAME': 'trupoll',
    'USER': 'root',
    'PASSWORD': '***********',
    'CONN_MAX_AGE': 500,
}
}
相关问题