Djangoの学習で、はまってしまったので、メモをします。
環境:Windows10 pro
Django version 3.1.4
Python 3.9
Djangoでブログを作成し、カテゴリを登録しようとしたら、以下のエラーが発生。
調べて、「OperationalError: no such table:○○ エラーの解決方法」が参考になりました。
db.sqlite3ファイルを削除
PS C:\Users\User\Django\project3> del db.sqlite3
admin.py、models.pyなどCategoryを記述した部分をコメントアウトする。
以下のコマンドを実行する。
py manage.py makemigrations app(作成したアプリ名)
py manage.py migrate
問題なければ、コメントアウトしたCategoryを解除する。
再度、以下のコマンド実行する。
py manage.py makemigrations app(作成したアプリ名)
You are trying to add a non-nullable field 'name' to category without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
- Provide a one-off default now (will be set on all existing rows with a null value for this column)
- Quit, and let me add a default in models.py
Select an option: 1 ←1と入力
Please enter the default value now, as valid Python
The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now
Type 'exit' to exit this prompt
1←1と入力
You are trying to add a non-nullable field 'category' to post without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
- Provide a one-off default now (will be set on all existing rows with a null value for this column)
- Quit, and let me add a default in models.py
Select an option: 1←1と入力
Please enter the default value now, as valid Python
The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now
Type 'exit' to exit this prompt
1←1と入力
再度、以下のコマンドを実行する。
py manage.py migrate
問題なければ、開発サーバを起動する。
py manage.py runserver
しかし、adminにログインできない。自前に管理ユーザーを作成したがdbを削除した時に消えたようです。
再度、管理ユーザーを作成。
py manage.py createsuperuser
再度、開発サーバを立ち上げて管理画面にログインできました。
カテゴリも正常に作成、追加が出来ました。