質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Django

DjangoはPythonで書かれた、オープンソースウェブアプリケーションのフレームワークです。複雑なデータベースを扱うウェブサイトを開発する際に必要な労力を減らす為にデザインされました。

Apache

Apacheは、Apache HTTP Serverの略で、最も人気の高いWebサーバソフトウェアの一つです。安定性が高いオープンソースソフトウェアとして商用サイトから自宅サーバまで、多くのプラットフォーム向けに開発・配布されています。サーバーソフトウェアの不具合(NCSA httpd)を修正するパッチ(a patch)を集積、一つ独立したソフトウェアとして開発されました。

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Amazon EC2

Amazon EC2は“Amazon Elastic Compute Cloud”の略称です。Amazon Web Services(AWS)の一部であり、仮想化されたWebサーバーのコンピュータリソースをレンタルできるサービスです。

Q&A

解決済

1回答

957閲覧

Django EC2 Apache 本番環境のみ画像のアップロードが行えない Pillowによるエラー

nika_nika

総合スコア38

Django

DjangoはPythonで書かれた、オープンソースウェブアプリケーションのフレームワークです。複雑なデータベースを扱うウェブサイトを開発する際に必要な労力を減らす為にデザインされました。

Apache

Apacheは、Apache HTTP Serverの略で、最も人気の高いWebサーバソフトウェアの一つです。安定性が高いオープンソースソフトウェアとして商用サイトから自宅サーバまで、多くのプラットフォーム向けに開発・配布されています。サーバーソフトウェアの不具合(NCSA httpd)を修正するパッチ(a patch)を集積、一つ独立したソフトウェアとして開発されました。

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Amazon EC2

Amazon EC2は“Amazon Elastic Compute Cloud”の略称です。Amazon Web Services(AWS)の一部であり、仮想化されたWebサーバーのコンピュータリソースをレンタルできるサービスです。

0グッド

0クリップ

投稿2022/05/10 13:32

編集2022/05/11 15:55

実現したいこと

画像をアップロードした時の500エラーを解決したい。

ローカル環境での画像アップロードは行えますが、本番環境だと画像をアップロードした時のみ500エラーが返ってきます。

追記
エラーの原因がPillow関連だということがわかりました。
Pillowをインストールしているはずですが、下記のエラーが出ます。
Pillowインストール時のpython3のバージョンと実行python3のバージョンは同じかと思います。
PILはインストールしておりません。

No module named 'PIL'

のエラーを解決したい。

本番環境

OS:mac
Django:3.2.10
Python:3.9
Linux
Django:3.2.12
python:3.7
MySQL:8.0
Apache:2.4.53
EC2
S3

コード

settings.py

1DATABASES = { 2 'default': { 3 'ENGINE': 'django.db.backends.mysql', 4 'NAME': 'xxxxxxxxxx', 5 'USER': 'xxxxxxxxxxx', 6 'PASSWORD': 'xxxxxxxxxx', 7 'HOST': 'xxxxxxxxxxxxxx.rds.amazonaws.com', 8 'PORT': '3306', 9 } 10} 11 12STATIC_URL = 'static/' 13 14# Default primary key field type 15# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field 16 17DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' 18 19#CSSの読み込み 20STATICFILES_DIRS = [ BASE_DIR / "static" ] 21 22#カスタムユーザーモデルをデフォルトに設定 23AUTH_USER_MODEL = 'register.User' 24#registerの設定 25LOGIN_URL = 'register:login' 26LOGIN_REDIRECT_URL = 'admin:top' 27LOGOUT_REDIRECT_URL = 'register:login' 28 29# 画像の読み込み 30# MEDIA_ROOT = os.path.join(BASE_DIR) 31 32# S3の設定 33 34AWS_LOCATION = 'static' 35 36DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' 37AWS_STORAGE_BUCKET_NAME = 'xxxxxxxx' 38AWS_S3_REGION_NAME = 'ap-northeast-1' 39 40AWS_ACCESS_KEY_ID = 'xxxxxxxxx' 41AWS_SECRET_ACCESS_KEY = 'xxxxxxxxxxxxx'

model.py

1 2 3def upload_image_to(instance, filename): 4 staff = str(instance.staff_id) 5 return os.path.join('static', 'images', staff, filename) 6 7class Staff(models.Model): 8 staff_id = models.BigAutoField(primary_key=True,validators=[MaxValueValidator(8)]) 9 staff_code = models.IntegerField() 10 staff_name = models.CharField(max_length=255) 11 staff_phone_1 = models.CharField(max_length=255,blank=True,null=True) 12 staff_sex = models.SmallIntegerField(validators=[MaxValueValidator(1)]) 13 staff_email = models.EmailField() 14 staff_login_password = models.CharField(max_length=255) 15 staff_status = models.SmallIntegerField(validators=[MaxValueValidator(2)],blank=True,null=True) 16 17 staff_image = models.ImageField(max_length=255, default='static/images/default.png', upload_to=upload_image_to)

views.py

1class StaffCreateForm(View): 2 3 return render(request,"pages/staffCreate.html",context) 4 5 def post(self, request): 6 posted = Staff( 7 staff_code = request.POST["staff_code"], 8 staff_name = request.POST["staff_name"], 9 staff_email = request.POST["staff_email"], 10 staff_login_password = request.POST["staff_login_password"], 11 staff_sex = request.POST["staff_sex"], 12 ) 13 staff_phone_1_result = request.POST["staff_phone_1"] 14 staff_status_result = request.POST["staff_status"] 15 staff_image_result = request.FILES.get("staff_image") 16 17 if not "" == staff_phone_1_result: 18 posted.staff_phone_1 = request.POST["staff_phone_1"] 19 20 if not "" == staff_status_result: 21 posted.staff_status= request.POST["staff_status"] 22 23#画像をアップロードしなかった際、デフォルトの画像を挿入 24 if None == staff_image_result: 25 posted.staff_image = str("static/images/default.png") 26 else: 27 posted.staff_image = request.FILES.get("staff_image") 28 29 posted.save() 30 31 return redirect("admin:staffList") 32 33class StaffEditForm(UpdateView): 34 35 template_name = 'pages/staffEdit.html' 36 model = Staff 37 fields = [ 38 'staff_code', 39 'staff_name', 40 'staff_email', 41 'staff_login_password', 42 'staff_sex', 43 'staff_phone_1', 44 'staff_status', 45 'staff_image', 46 ] 47 48 def get_success_url(self): 49 return reverse('admin:staffList')

staffCreate.html

1<div class="p-staff__formBox"> 2 <p class="p-staff__formText">画像</p> 3 <div class="p-staff__imageBlock"> 4 <div class="p-staff__imageTest"> 5 6 <!-- デフォルト画像 --> 7 <img id="no_image" class="{% if staff.staff_image != none %}hidden{% endif %}" src="https://xxxxxxxxx.amazonaws.com/static/images/default.png"> 8 <!-- 画像がある場合 --> 9 <img id="image_preview" class="{% if staff.staff_image == none %}hidden{% endif %}" src="https://xxxxxxxxxxxx.amazonaws.com/{{ staff.staff_image }}"> 10 11 </div> 12 <label class="p-staff-imageLabel"> 13 画像をアップロード 14 <input class="p-staff__imageBtn" type="file" accept=".png, .jpeg, .jpg, .gif, .img" name="staff_image" onchange="previewImage(this)"> 15 </label> 16 </div> 17</div> 18 19<!-- プレビュー --> 20<script> 21 function previewImage(elem) { 22 let fileReader = new FileReader(); 23 fileReader.onload = (function(){ 24 document.getElementById('image_preview').classList.remove('hidden'); 25 document.getElementById('no_image').classList.add('hidden'); 26 27 document.getElementById('image_preview').src = fileReader.result; 28 }) 29 fileReader.readAsDataURL(elem.files[0]); 30 } 31</script>

etc/httpd/conf.d/アプリ名.conf

1"/etc/httpd/conf.d/アプリ名.conf" 18L, 503B 9,15 全て 2LoadModule wsgi_module /usr/local/lib64/python3.7/site-packages/mod_wsgi/server/mod_wsgi-py37.cpython-37m-x86_64-linux-gnu.so 3 4ServerName xx.xx.xxx.xxx 5 6WSGIScriptAlias / /home/ec2-user/アプリ名/config/wsgi.py 7WSGIPythonPath /home/ec2-user/アプリ名:/usr/bin/python3 8 9Alias /static/ /home/ec2-user/アプリ名/static/ 10<Directory /home/ec2-user/アプリ名/static> 11Require all granted 12</Directory> 13 14<Directory /home/ec2-user/アプリ名/config> 15<Files wsgi.py> 16Require all granted 17</Files> 18</Directory> 19

試したこと

DBの初期化やsettings.pyのSTATIC_URLのパスを変えたりしてみましたが、解決できませんでした。
画像アップロード時のみ500エラーが出る事象がネットに転がっていなかったため、皆様のお力を借りたいです。よろしくお願い致します。
足りない記述やエラーの要因になりそうなものがありましたら、教えていただけると幸いです。

追記

エラー文

ModuleNotFoundError at /admin/staff/edit/2 No module named 'PIL' Request Method: POST Request URL: http://xx.xx.xxx.xxx/admin/staff/edit/2 Django Version: 3.2.12 Exception Type: ModuleNotFoundError Exception Value: No module named 'PIL' Exception Location: /usr/local/lib/python3.7/site-packages/django/forms/fields.py, line 631, in to_python Python Executable: /usr/bin/python3 Python Version: 3.7.10 Python Path: ['/home/ec2-user/アプリ名', '/usr/bin/python3', '/usr/lib64/python37.zip', '/usr/lib64/python3.7', '/usr/lib64/python3.7/lib-dynload', '/usr/local/lib64/python3.7/site-packages', '/usr/local/lib/python3.7/site-packages', '/usr/lib64/python3.7/site-packages', '/usr/lib/python3.7/site-packages'] Server time: Tue, 10 May 2022 14:57:42 +0000

python

1$ python3 2Python 3.7.10 (default, Jun 3 2021, 00:02:01) 3[GCC 7.3.1 20180712 (Red Hat 7.3.1-13)] on linux 4Type "help", "copyright", "credits" or "license" for more information. 5>>> import pillow 6Traceback (most recent call last): 7 File "<stdin>", line 1, in <module> 8ModuleNotFoundError: No module named 'pillow' 9>>> import PIL 10>>>

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

kyokio

2022/05/10 14:35

エラー文を見たいです
nika_nika

2022/05/10 14:52 編集

ご質問ありがとうございます。 画像アップロード時のエラー文は、「Server Error (500)」の画面表示のみになります。 Apacheのエラーログを見ようとしたのですが、方法がわからず sudo less /var/log/httpd/error_log コマンドで 下記のログは、確認できたのですがあまり関係ないですよね。。 ``` mands in this regard and the currently selected mpm will just not do. This is an advisory warning. Your server will continue to work, but the HTTP/2 protocol will be inactive. [Mon May 09 15:48:44.863861 2022] [mpm_prefork:notice] [pid 12778] AH00163: Apache/2.4.52 () mod_wsgi/4.9.0 Python/3.7 configured -- resuming normal operations [Mon May 09 15:48:44.863887 2022] [core:notice] [pid 12778] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND' [Mon May 09 16:10:18.074586 2022] [mpm_prefork:notice] [pid 12778] AH00170: caught SIGWINCH, shutting down gracefully [Mon May 09 16:10:19.179849 2022] [suexec:notice] [pid 13038] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec) [Mon May 09 16:10:19.207102 2022] [lbmethod_heartbeat:notice] [pid 13038] AH02282: No slotmem from mod_heartmonitor [Mon May 09 16:10:19.207148 2022] [http2:warn] [pid 13038] AH10034: The mpm module (prefork.c) is not supported by mod_http2. The mpm determines how things are processed in your server. HTTP/2 has more demands in this regard and the currently selected mpm will just not do. This is an advisory warning. Your server will continue to work, but the HTTP/2 protocol will be inactive. [Mon May 09 16:10:19.211148 2022] [mpm_prefork:notice] [pid 13038] AH00163: Apache/2.4.53 () mod_wsgi/4.9.0 Python/3.7 configured -- resuming normal operations [Mon May 09 16:10:19.211170 2022] [core:notice] [pid 13038] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND' [Tue May 10 00:33:51.467537 2022] [cgi:error] [pid 13040] [client 46.101.157.178:34400] AH02811: script not found or unable to stat: /var/www/cgi-bin/php ```
kyokio

2022/05/10 14:53

デバッグtrueにしてエラー内容をみてはいかがでしょうか?
nika_nika

2022/05/10 15:03 編集

デバッグtrueでエラー分がでることを知っておりませんでした。ありがとうございます! ModuleNotFoundError at /admin/staff/edit/2 No module named 'PIL' 上記のエラーが出ました。 pillow インストールしていたかと思ったのですが、確認してみます。 Pillow : 9.1.0はインストールされていました。
nika_nika

2022/05/10 15:13

実行時のpythonバージョンが異なっていることによるエラーなのでしょうか。
kyokio

2022/05/10 15:17

pipで入れました? pipとDjangoを実行しているpythonは同じですか?
nika_nika

2022/05/10 15:30

pipでPillowをインストールしました。 Pillowの保存先は/home/ec2-user/.local/lib/python3.7/site-packages で pythonのバージョンを確認すると python3 --versionコマンドで Python 3.7.10 と表示されました。 本番環境でのpipとDjangoの実行しているpythonは上記の確認で同じかなと判断しているのですがいかがでしょうか。 本題の質問で環境python3.9と記述しているのは、自身のPC環境を記述していたみたいでした。すみません。
kyokio

2022/05/11 07:26

本番環境のOSはmacなんですか? pip list Djangoのバージョンは幾つですか?
nika_nika

2022/05/11 13:12

失礼しました。Linuxになります。 pip list Djangoのバージョンは3.2.12になります。
kyokio

2022/05/11 14:16 編集

path関係でないなら今の情報ではわからないです。 もし、github等にコードが公開しているなら検証しますが、、、 あと、下記サイトにpillowとPILは共存できないと書いてあるので確認してみてはいかがでしょうか https://note.nkmk.me/python-pillow-basic/
nika_nika

2022/05/11 14:20

色々考えてくれて誠にありがとうございます。 こちら、業務で使用しておりプライベート環境のため共有ができないです。 ありがとうございます。 参考サイト拝見いたします! 何か変化あれば追記いたします!!
guest

回答1

0

自己解決

kyokioさんのおかげで、解決につながりました。誠にありがとうございます。

Pillowのインストール先が間違っていたためエラーが起きていました。

$ pip3 show Pillow Location: /home/ec2-user/.local/lib/python3.7/site-packages $ pip3 uninstall Pillow $ which pip ~/.local/bin/pip ~/.local/bin/pip install Pillow $ pip3 show Pillow Location: /usr/local/lib64/python3.7/site-packages

インストール先が変わる理由などわかる方いましたら、教えて頂きたいです。

投稿2022/05/12 02:35

nika_nika

総合スコア38

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問