@irebasunglass213

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

マイグレートのエラー

Djangoがマイグレートできない

アプリを作成中ログイン機能を導入したくてAbstractUserを継承した
CostomUserモデルを作成しました.

models.pyの表記は以下です。

models.py

from django.contrib.auth.models import AbstractUser
from django.db import models

class CustomUser(AbstractUser):
    # 追加のユーザーフィールドを定義
    # 例: profile_picture = models.ImageField(upload_to='profile_pics/', null=True, blank=True)
    pass

class Char_Script(models.Model):
    char = models.CharField(max_length=100)
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)  # ForeignKeyでCustomUserとの関連を表現
    nickname = models.CharField(max_length=100)
    quote = models.CharField(max_length=100)

    class Meta:
        db_table = 'char'

    def __str__(self):
        return self.char

既存のChar_Scriptがある中で新たにCustomUserもでるを作り二つのモデルを紐づかせている?
のような状態です。

python manage.py makemigrationsコマンドで
下記のようなマイグレーションファイルを作成しました。

0003_customuser_alter_char_script_user.py
# Generated by Django 5.0.1 on 2024-02-08 06:10

import django.contrib.auth.models
import django.contrib.auth.validators
import django.db.models.deletion
import django.utils.timezone
from django.conf import settings
from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('auth', '0012_alter_user_first_name_max_length'),
        ('fb_app', '0002_char_script_nickname_char_script_quote'),
    ]

    operations = [
        migrations.CreateModel(
            name='CustomUser',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('password', models.CharField(max_length=128, verbose_name='password')),
                ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
                ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
                ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')),
                ('first_name', models.CharField(blank=True, max_length=150, verbose_name='first name')),
                ('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')),
                ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')),
                ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
                ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
                ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
                ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.group', verbose_name='groups')),
                ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.permission', verbose_name='user permissions')),
            ],
            options={
                'verbose_name': 'user',
                'verbose_name_plural': 'users',
                'abstract': False,
            },
            managers=[
                ('objects', django.contrib.auth.models.UserManager()),
            ],
        ),
        migrations.AlterField(
            model_name='char_script',
            name='user',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
        ),
    ]

問題はここからpython manage.py migrateコマンドを実行すると
以下のようなエラーが出ます。

発生している問題・エラー

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, fb_app, sessions  
Traceback (most recent call last):
  File "C:\Users\ireba\fb_players\manage.py", line 22, in <module>   
    main()
  File "C:\Users\ireba\fb_players\manage.py", line 18, in main       
    execute_from_command_line(sys.argv)
  File "C:\Users\ireba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line
    utility.execute()
  File "C:\Users\ireba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 436, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\ireba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\base.py", line 412, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\ireba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\base.py", line 458, in execute    
    output = self.handle(*args, **options)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ireba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\base.py", line 106, in wrapper    
    res = handle_func(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ireba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\commands\migrate.py", line 302, in handle
    pre_migrate_apps = pre_migrate_state.apps
                       ^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ireba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\functional.py", line 47, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
                                         ^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ireba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\migrations\state.py", line 566, in apps        
    return StateApps(self.real_apps, self.models)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ireba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\migrations\state.py", line 637, in __init__    
    raise ValueError("\n".join(error.msg for error in errors))       
ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'fb_app.customuser', but app 'fb_app' doesn't provide model 'customuser'.

調べているとこれはCustomUserモデルがみつからないというエラーなのが分かりました

自分で試したこと

setting.pyにAUTH_USER_MODEL = 'fb_app.CustomUser' と記述いたしました。

該当するソースコード

setting.py
AUTH_USER_MODEL = 'fb_app.CustomUser'  #fb_appというアプリ

adminファイルに以下のようにコードを記述いたしました。

例)

admin.py
# Register your models here.

from django.contrib import admin
from .models import CustomUser

admin.site.register(CustomUser)

しかしこれもデバッグすると


c:/Users/ireba/fb_players/fb_app/admin.py
Traceback (most recent call last):
  File "c:\Users\ireba\fb_players\fb_app\admin.py", line 5, in <module>
    from .models import CustomUser
ImportError: attempted relative import with no known parent package
PS C:\Users\ireba\fb_players> 

相対パスの打ち方を変えてみても

admin.py
# Register your models here.

from django.contrib import admin
from fb_app.models import CustomUser #from .models import CustomUserから変更

admin.site.register(CustomUser)

c:/Users/ireba/fb_players/fb_app/admin.py
Traceback (most recent call last):
  File "c:\Users\ireba\fb_players\fb_app\admin.py", line 5, in <module>
    from fb_app.models import CustomUser
ModuleNotFoundError: No module named 'fb_app'


となります

ちなみにmodels.pyをデバッグしても

C:/Users/ireba/AppData/Local/Programs/Python/Python311/python.exe c:/Users/ireba/fb_players/fb_app/models.py
Traceback (most recent call last):
  File "c:\Users\ireba\fb_players\fb_app\models.py", line 1, in <module>
    from django.contrib.auth.models import AbstractUser
  File "C:\Users\ireba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\contrib\auth\models.py", line 3, in <module>      
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "C:\Users\ireba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\contrib\auth\base_user.py", line 58, in <module>  
    class AbstractBaseUser(models.Model):
  File "C:\Users\ireba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\base.py", line 129, in __new__
    app_config = apps.get_containing_app_config(module)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ireba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\apps\registry.py", line 260, in get_containing_app_config
    self.check_apps_ready()
  File "C:\Users\ireba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\apps\registry.py", line 137, in check_apps_ready  
    settings.INSTALLED_APPS
  File "C:\Users\ireba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\conf\__init__.py", line 89, in __getattr__        
    self._setup(name)
  File "C:\Users\ireba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\conf\__init__.py", line 69, in _setup
    raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

モデルが正常に機能してないのでしょうか?

よろしくお願いいたします。

0 likes

1Answer

1つ目のエラー

1つ目のエラーは、admin.LogEntryモデルが、fb_appにあるCustomUserモデルを参照しようとしたときに、CustomUser のマイグレーションがまだ適用されていないため、Djangoはfb_appでそのモデルを見つけることができませんと言ってます。

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, fb_app, sessions  
Traceback (most recent call last):
  File "C:\Users\ireba\fb_players\manage.py", line 22, in <module>   
    main()
  File "C:\Users\ireba\fb_players\manage.py", line 18, in main       
    execute_from_command_line(sys.argv)
  File "C:\Users\ireba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line
    utility.execute()
  File "C:\Users\ireba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 436, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\ireba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\base.py", line 412, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\ireba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\base.py", line 458, in execute    
    output = self.handle(*args, **options)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ireba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\base.py", line 106, in wrapper    
    res = handle_func(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ireba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\commands\migrate.py", line 302, in handle
    pre_migrate_apps = pre_migrate_state.apps
                       ^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ireba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\functional.py", line 47, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
                                         ^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ireba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\migrations\state.py", line 566, in apps        
    return StateApps(self.real_apps, self.models)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ireba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\migrations\state.py", line 637, in __init__    
    raise ValueError("\n".join(error.msg for error in errors))       
ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'fb_app.customuser', but app 'fb_app' doesn't provide model 'customuser'.

fb_appディレクトリ内で、以下のコマンドを実行して新しいマイグレーションファイルを作成してください。

$ python manage.py makemigrations fb_app

その次に以下のコマンドでマイグレートしてDBに適用します。

$ python manage.py migrate

2つ目のエラー

2つ目のエラーは、fb_appディレクトリがPythonパッケージとして認識されていないことが原因です。

c:/Users/ireba/fb_players/fb_app/admin.py
Traceback (most recent call last):
  File "c:\Users\ireba\fb_players\fb_app\admin.py", line 5, in <module>
    from .models import CustomUser
ImportError: attempted relative import with no known parent package
PS C:\Users\ireba\fb_players> 

fb_appディレクトリ内に__init__.pyファイルが存在していない場合追加してください。

3つ目のエラー

3つ目のエラーは、fb_app ディレクトリが Python のパスにない場合、または別のディレクトリからスクリプトを実行している場合に発生します。

c:/Users/ireba/fb_players/fb_app/admin.py
Traceback (most recent call last):
  File "c:\Users\ireba\fb_players\fb_app\admin.py", line 5, in <module>
    from fb_app.models import CustomUser
ModuleNotFoundError: No module named 'fb_app'

設定ディレクトリが、manage.pyと同じ階層に配置しているか確認してください。

4つ目のエラー

4つ目のエラーは、INSTALLED_APPSにアクセスしようとしているが、設定されていないことが原因です。

C:/Users/ireba/AppData/Local/Programs/Python/Python311/python.exe c:/Users/ireba/fb_players/fb_app/models.py
Traceback (most recent call last):
  File "c:\Users\ireba\fb_players\fb_app\models.py", line 1, in <module>
    from django.contrib.auth.models import AbstractUser
  File "C:\Users\ireba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\contrib\auth\models.py", line 3, in <module>      
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "C:\Users\ireba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\contrib\auth\base_user.py", line 58, in <module>  
    class AbstractBaseUser(models.Model):
  File "C:\Users\ireba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\base.py", line 129, in __new__
    app_config = apps.get_containing_app_config(module)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ireba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\apps\registry.py", line 260, in get_containing_app_config
    self.check_apps_ready()
  File "C:\Users\ireba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\apps\registry.py", line 137, in check_apps_ready  
    settings.INSTALLED_APPS
  File "C:\Users\ireba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\conf\__init__.py", line 89, in __getattr__        
    self._setup(name)
  File "C:\Users\ireba\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\conf\__init__.py", line 69, in _setup
    raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

設定ディレクトリのsettings.pyのINSTALLD_APPSのリストに’fb_app’というアプリを追加してください。
また、settings.pyの場所を変更している場合は、DJANGO_SETTINGS_MODULE環境変数の文字列をsettings.pyのある場所のパスに変更してください。

0Like

Comments

  1. ありがとうございます。 マイグレーション無事にできました。

Your answer might help someone💌