将 Django 应用程序部署到 heroku。调试错误

时间:2021-01-14 00:00:57

标签: django heroku deployment

我正在尝试将我的应用程序部署到 heroku。 我在处理了一些错误后成功部署到应用程序(CSS 无法加载,或图像无法加载)。现在,当我部署应用程序时,当 DEBUG = True 时工作正常。 当我更改 DEBUG = False 时,所有图像都无法加载。

这是我的代码: 设置.py

"""
Django settings for DBSF project.

Generated by 'django-admin startproject' using Django 3.1.2.

For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""

from pathlib import Path
import django_heroku
import os
from dotenv import load_dotenv
load_dotenv()
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ['SECRET_KEY']
AUTH_USER_MODEL = 'social.User'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['desolate-lowlands-74512.herokuapp.com', 'localhost', '127.0.0.1']

# Application definition

INSTALLED_APPS = [
    'channels',
    'social',
    '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 = 'DBSF.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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',
            ],
        },
    },
]

REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
    ]
}

WSGI_APPLICATION = 'DBSF.wsgi.application'
ASGI_APPLICATION = 'DBSF.asgi.application'
CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            "hosts": [('127.0.0.1', 6379)],
        },
    },
}

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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.1/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/3.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'EST'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
MEDIA_ROOT= os.path.join(BASE_DIR, 'media/')
MEDIA_URL= "/media/"

这里是 asgi.py

"""
ASGI config for DBSF project.

It exposes the ASGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
import social.routing

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DBSF.settings')

application = ProtocolTypeRouter({
    "http": get_asgi_application(),
    "websocket": AuthMiddlewareStack(
        URLRouter(
            social.routing.websocket_urlpatterns
        )
    ),
})

这里是 wsgi.py

"""
WSGI config for DBSF project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DBSF.settings')

application = get_wsgi_application()

这里是 procfile.windows


web: python manage.py runserver 0.0.0.0:5000

这里是 procfile

web: gunicorn DBSF.wsgi

这里是 layout.html

{% load static %}
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
    <script type='text/babel' src="{% static 'social/javascript/react_components.js' %}"></script>
    <script type="text/babel" src="{% static 'social/javascript/layout.js' %}"></script>
    <script src="https://cdn.jsdelivr.net/npm/js-cookie@rc/dist/js.cookie.min.js"></script>
    {% block head %}{% endblock %}
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Tangerine">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="{% static 'social/styles/base.css' %}">
    <link rel="shortcut icon" type="image/png" href="{% static 'social/favicon/favicon.ico' %}"/>
    <title>{% block title %}{% endblock %}</title>
  </head>
  <body>
    <nav class='main_nav'>
      <a href="{% url 'index' %}" title='homepage'>DBSF</a>
      <form action="/find_friends" method="GET">
        <input name='search_term' type='text' placeholder='Search for friends'>
        <input class='search_friends_button' type="submit" value='&#x1F50D;'></form>
      <a href="{% url 'profile' %}">
        {% if user.profile_pic.url != '' %}
          <img class="profile_pic_small_icon" src="{{user.profile_pic.url}}" alt="profile_pic">
        {% else %}
          <img class='profile_pic_small_icon' src="{% static 'social/core_images/no_image.jpg' %}" alt="{{user}} hasn't uploaded an image yet">  
        {% endif %}
        {{user|title}}
      </a>
      <a href="#">Messages</a>
      <form class="logout_form" action="{% url 'logout' %}" method="post">
        {% csrf_token %}
        <a class='logout_a' href="/logout">Log out</a>
      </form>
    </nav>
    <div class="messages">
      <h1>{{message}}</h1>
    </div>
    <div class="side_bar">
      <h4>Friend Requests</h4>  
      <div id="friendship_request_div"></div> 
    </div>
    <div class="main">
      {% block body %}{% endblock %}
    </div>
    <div class="friends_right_div">
      <h4>Friends</h4>
      <div id='friendship_div'></div>
    </div>
    <div id='message_box' class='message_box'>
    </div>
  </body>
</html>

所以基本上我需要弄清楚为什么 DEBUG = False 不允许加载图像。 让我知道我的要求是否清楚,或者您是否需要任何其他文件来帮助我! 谢谢

1 个答案:

答案 0 :(得分:0)

尝试将其放入您的 @Param

urls.py

这在您的 from django.views.static import serve 中:

urlpatterns

在生产中,您通常会使用 nginx 或其他服务来提供媒体文件(如图像)。如果您只是想以一种快速而肮脏的方式仍然使用 url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}), 查看它们,那么这应该将媒体路由添加到 url 模式中。

相关问题