質問編集履歴

1 フォルダ名を編集

wasshoi

wasshoi score 7

2020/10/22 12:21  投稿

Djangoにて、管理画面からデータを追加しようとすると外部キー制約エラーが発生する
PythonのフレームワークDjangoの勉強で日記を登録するwebサイトを開発しています。
管理画面(adminページ)からDiaryテーブルへデータを追加/更新/削除をしようとすると[FOREIGN KEY constraint failed]と表示され、正常に処理がされません。
直接[python manage.py shell]からDBにデータを追加/更新/削除を実施したところ、正常に処理が行えましたので、本当に外部キー制約により、問題が発生しているのか、判断がつきません。
解決方法に心当たりがある方がいましたら、考えて頂けないでしょうか。
下記にmodelsファイルを記載します。
mysite>
------>accounts>models.py
------>diary>models.py
**accounts.models**
```python
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
   class Meta:
       verbose_name_plural = 'CustomUser'
```
**diary.models**
```python
from accounts.models import CustomUser
from django.db import models
class Diary(models.Model):
   user = models.ForeignKey(CustomUser,
                            verbose_name='ユーザー', on_delete=models.PROTECT)
   title = models.CharField(verbose_name='タイトル', max_length=40)
   content = models.TextField(verbose_name='本文', blank=True, null=True)
   photo1 = models.ImageField(verbose_name='写真1', blank=True, null=True)
   photo2 = models.ImageField(verbose_name='写真2', blank=True, null=True)
   photo3 = models.ImageField(verbose_name='写真3', blank=True, null=True)
   created_at = models.DateTimeField(verbose_name='作成日時', auto_now_add=True)
   updated_at = models.DateTimeField(verbose_name='更新日時', auto_now=True)
   class Meta:
       verbose_name_plural = 'Diary'
       def __str__(self):
           return self.title
```
**エラーメッセージ**
```
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/diary/diary/3/change/
Django Version: 3.0.10
Python Version: 3.8.6
Installed Applications:
['accounts.apps.AccountsConfig',
'diary.apps.DiaryConfig',
'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']
Installed 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']
Traceback (most recent call last):
 File "C:\Users\koki\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\db\backends\base\base.py", line 243, in _commit
   return self.connection.commit()
The above exception (FOREIGN KEY constraint failed) was the direct cause of the following exception:
 File "C:\Users\koki\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\handlers\exception.py", line 34, in inner
 File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\handlers\exception.py", line 34, in inner
   response = get_response(request)
 File "C:\Users\koki\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\handlers\base.py", line 115, in _get_response
 File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\handlers\base.py", line 115, in _get_response
   response = self.process_exception_by_middleware(e, request)
 File "C:\Users\koki\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\handlers\base.py", line 113, in _get_response
 File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\handlers\base.py", line 113, in _get_response
   response = wrapped_callback(request, *callback_args, **callback_kwargs)
 File "C:\Users\koki\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\contrib\admin\options.py", line 607, in wrapper
 File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\contrib\admin\options.py", line 607, in wrapper
   return self.admin_site.admin_view(view)(*args, **kwargs)
 File "C:\Users\koki\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
 File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
   response = view_func(request, *args, **kwargs)
 File "C:\Users\koki\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
 File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
   response = view_func(request, *args, **kwargs)
 File "C:\Users\koki\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\contrib\admin\sites.py", line 231, in inner
 File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\contrib\admin\sites.py", line 231, in inner
   return view(request, *args, **kwargs)
 File "C:\Users\koki\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\contrib\admin\options.py", line 1641, in change_view
 File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\contrib\admin\options.py", line 1641, in change_view
   return self.changeform_view(request, object_id, form_url, extra_context)
 File "C:\Users\koki\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\utils\decorators.py", line 43, in _wrapper
 File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\utils\decorators.py", line 43, in _wrapper
   return bound_method(*args, **kwargs)
 File "C:\Users\koki\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
 File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
   response = view_func(request, *args, **kwargs)
 File "C:\Users\koki\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\contrib\admin\options.py", line 1522, in changeform_view
 File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\contrib\admin\options.py", line 1522, in changeform_view
   return self._changeform_view(request, object_id, form_url, extra_context)
 File "C:\Users\koki\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\db\transaction.py", line 232, in __exit__
 File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\db\transaction.py", line 232, in __exit__
   connection.commit()
 File "C:\Users\koki\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\utils\asyncio.py", line 26, in inner
 File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\utils\asyncio.py", line 26, in inner
   return func(*args, **kwargs)
 File "C:\Users\koki\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\db\backends\base\base.py", line 267, in commit
 File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\db\backends\base\base.py", line 267, in commit
   self._commit()
 File "C:\Users\koki\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\db\backends\base\base.py", line 243, in _commit
 File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\db\backends\base\base.py", line 243, in _commit
   return self.connection.commit()
 File "C:\Users\koki\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\db\utils.py", line 90, in __exit__
 File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\db\utils.py", line 90, in __exit__
   raise dj_exc_value.with_traceback(traceback) from exc_value
 File "C:\Users\koki\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\db\backends\base\base.py", line 243, in _commit
 File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\db\backends\base\base.py", line 243, in _commit
   return self.connection.commit()
Exception Type: IntegrityError at /admin/diary/diary/3/change/
Exception Value: FOREIGN KEY constraint failed
```
  • Python

    38038 questions

    Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

  • SQLite

    1429 questions

    SQLiteはリレーショナルデータベース管理システムの1つで、サーバーではなくライブラリとして使用されている。

  • Django

    4652 questions

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

思考するエンジニアのためのQ&Aサイト「teratail」について詳しく知る