python - Dango 应用程序未在 Heroku 上正确部署:DEBUG=False 时服务器错误 500,DEBUG=True 时未正确加载索引视图
问题描述
在本地,我的 Django 应用程序运行良好。
我能够在 Heroku 上部署应用程序,但是在 setting.py 中,当 DEBUG=False 时,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 加载了一个页面,上面写着“没有可用的民意调查”。这是来自我的根/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 部署所做的 settings.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
我的网站/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'
我的网站/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')),
]
民意调查/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
民意调查/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'),
]
民意调查/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())
民意调查/模板/民意调查/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>
模板/管理员/base_site.html
{% block branding %}
<h1 id="site-name"><a href="{% url 'admin:index' %}">PyPoll Administration</a></h1>
{% endblock %}
解决方案
看起来您需要创建一个数据库。幸运的是 Heroku 有一个简单的方法来做到这一点。用您选择的提供商提供给您的信用替换以下内容。我相信如果你想要MySql CLEARDB 会是一个不错的选择。祝你好运,我希望这会有所帮助。
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST': '',
'PORT': '',
'NAME': 'trupoll',
'USER': 'root',
'PASSWORD': '***********',
'CONN_MAX_AGE': 500,
}
}
推荐阅读
- corda - 执行 VaultQuery
- python - 在构建和训练 3D Keras U-NET 时遇到 ValueError
- node.js - MongoDB upsert 创建另一个实例
- jquery - 单选按钮在 jquery formbuilder 中不起作用
- airflow - Airflow:如何取出一个现在没有包含在 DAG 中的任务?
- flutter - Flutter - 如何在 sliverappbar 中添加自定义标签栏?
- javascript - Cypress Cucumber Step 运行多个步骤
- android - 如何更改已知项目保存在 SharedPrefrence 中并将图标设置为菜单中的收藏夹?
- powerbi - 如果为空则跳过一条记录
- eclipse - 更改scala编译器版本时找不到或加载主类错误