Django×apache2 本番環境 画像保存時 エラー500発生
解決したいこと
・Djangoでブログアプリを作っています。
・記事に画像を登録できるようにし、開発環境では問題なく機能しています。
・sakuraのVPSにデプロイし、webサーバーはapache2で本番環境を構築しています。
・本番環境にて新規記事を投稿したところ、文字だけの記事は登録できたのですが、画像を登録しようとすると、ブラウザにエラー500が発生しました。
いろいろ試してみたのですが、状況が変わらず困っています。どなたかよい解決方法やアイデアございましたら、是非教えて下さい。
発生している問題・エラー
【ブラウザ】
Server Error (500)
【apache error.log】
root@ik1-413-38954:/Nippo/site/logs# cat error.log
Exception ignored in: <function Local.__del__ at 0x7fbddb723d30>
Traceback (most recent call last):
File "/Nippo/venv/lib/python3.8/site-packages/asgiref/local.py", line 94, in __del__
NameError: name 'TypeError' is not defined
...省略
該当するソースコード
※apacheのconf
(venv) root@ik1-413-38954:/etc/apache2/sites-available# cat Nippo.conf
<VirtualHost *>
# The ServerName directive sets the request scheme, hostname and port that
# the server uses to identify itself. This is used when creating
# redirection URLs. In the context of virtual hosts, the ServerName
# specifies what hostname must appear in the request's Host: header to
# match this virtual host. For the default virtual host (this file) this
# value is not decisive as it is used as a last resort host regardless.
# However, you must set it for any further virtual host explicitly.
#ServerName www.example.com
ServerAdmin sample@example.com
DocumentRoot /Nippo
ErrorLog /Nippo/site/logs/error.log
CustomLog /Nippo/site/logs/access.log combined
alias /static /Nippo/site/public/static
<Directory /Nippo/site/public/static/>
Require all granted
</Directory>
alias /media /Nippo/site/public/media
<Directory /Nippo/site/public/media/>
Require all granted
</Directory>
<Directory /Nippo/src/main/>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
WSGIDaemonProcess nippoapp python-path=/Nippo/src python-home=/Nippo/venv
WSGIProcessGroup nippoapp
WSGIScriptAlias / /Nippo/src/main/wsgi.py
# Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the loglevel for particular
# modules, e.g.
#LogLevel info ssl:warn
#ErrorLog ${APACHE_LOG_DIR}/error.log
#CustomLog ${APACHE_LOG_DIR}/access.log combined
# For most configuration files from conf-available/, which are
# enabled or disabled at a global level, it is possible to
# include a line for only one particular virtual host. For example the
# following line enables the CGI configuration for this host only
# after it has been globally disabled with "a2disconf".
#Include conf-available/serve-cgi-bin.conf
※Djangoのsettings
(venv) root@ik1-413-38954:/Nippo/src/main/settings# cat base.py
"""
Django settings for main project.
Generated by 'django-admin startproject' using Django 4.1.3.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""
from pathlib import Path
from django.urls import reverse_lazy
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent.parent
PARENT_DIR = Path(__file__).resolve().parent.parent.parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['***','localhost']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'nippo',
'accounts',
'crispy_forms',
'bootstrap4',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'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 = 'main.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [ 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.media',
],
},
},
]
WSGI_APPLICATION = 'main.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
with open(f'{PARENT_DIR}/auth/***') as f:
*** = f.read().strip()
with open(f'{PARENT_DIR}/auth/***') as f:
*** = f.read().strip()
with open(f'{PARENT_DIR}/auth/***') as f:
*** = f.read().strip()
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': ***,
'USER': ***,
'PASSWORD': ***,
'HOST': 'localhost',
'PORT': '5432',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.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/4.1/topics/i18n/
LANGUAGE_CODE = 'ja'
TIME_ZONE = 'Asia/Tokyo'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / "static_local" ]
STATIC_ROOT = PARENT_DIR / 'site/public/static'
MEDIA_URL = '/media/'
MEDIA_ROOT = PARENT_DIR / "site/public/media"
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
AUTH_USER_MODEL = 'accounts.User'
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend',
]
SITE_ID = 1
ACCOUNT_USER_MODEL_USERNAME_FIELD = None
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_REQUIRED = True
LOGIN_REDIRECT_URL = reverse_lazy('nippo-list')
ACCOUNT_LOGOUT_REDIRECT_URL = reverse_lazy("account_login")
ACCOUNT_EMAIL_VERIFICATION = "none"
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
CRISPY_TEMPLATE_PACK = 'bootstrap4'
ACCOUNT_LOGOUT_ON_GET = True
BOOTSTRAP4 = {
'include_jquery': True,
}
Nippo ※VPSのトップディレクトリに置いています
├── README.md
├── auth
├── requirements.txt
├── site
│ ├── logs
│ └── public
│ ├── media
│ │ ├── pages
│ │ └── images
│ └── static
├── src ※中身:accounts db.sqlite3 main manage.py media_local nippo requirements.txt static_local templates
└── venv
自分で試したこと
※各項目実施ごとにブラウザのキャッシュを削除して実行しました
1.apacheのconf書き換え
<VirtualHost *:80> ⇒ <VirtualHost *>
(参考サイト)https://forum.djangoproject.com/t/deploy-to-apache/5208/20
2.VPSで、group_name nippoapp、user_name root 登録
(参考サイト)https://www.monotalk.xyz/blog/centos-74-apache-python-%E9%80%A3%E6%90%BA%E6%99%82%E3%81%AB%E3%81%A4%E3%81%BE%E3%81%A5%E3%81%84%E3%81%9F%E3%81%A8%E3%81%93%E3%82%8D/
3.Pillowのインストール先の変更
(参考サイト)tps://teratail.com/questions/amrloy7ulp9v52
4.chmodユーザー権限設定
chmod g+x /Nippo
chmod g+x /Nippo/site
chmod g+x /Nippo/site/public
chmod g+x /Nippo/site/public/pages
chmod g+x /Nippo/site/public/images