簡體   English   中英

Django 管理員:自定義用戶 model 在 app 部分而不是 auth 部分

[英]Django Admin: Custom User model in app section instead of auth section

問題 36046698 一樣,我在models.py中定義了一個 CustomUser model 。

我希望它出現在 Django Admin 的Authentication & Authorization部分。

我嘗試按照建議添加 app_label = 'auth' ,即

class CustomUser(AbstractUser):
    class Meta:
        app_label = 'auth'

當我這樣做時,我的應用程序將無法啟動,並且錯誤如下:

Traceback (most recent call last):
  File "/Users/paul/myapp/.direnv/python-3.8.5/lib/python3.8/site-packages/django/apps/config.py", line 178, in get_model
    return self.models[model_name.lower()]
KeyError: 'customuser'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/paul/myapp/.direnv/python-3.8.5/lib/python3.8/site-packages/django/contrib/auth/__init__.py", line 157, in get_user_model
    return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False)
  File "/Users/paul/myapp/.direnv/python-3.8.5/lib/python3.8/site-packages/django/apps/registry.py", line 211, in get_model
    return app_config.get_model(model_name, require_ready=require_ready)
  File "/Users/paul/myapp/.direnv/python-3.8.5/lib/python3.8/site-packages/django/apps/config.py", line 180, in get_model
    raise LookupError(
LookupError: App 'myapp' doesn't have a 'CustomUser' model.

During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "/Users/paul/myapp/.direnv/python-3.8.5/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
....
  File "/Users/paul/myapp/myapp/admin.py", line 3, in <module>
    from django.contrib.auth.admin import UserAdmin
  File "/Users/paul/myapp/.direnv/python-3.8.5/lib/python3.8/site-packages/django/contrib/auth/admin.py", line 6, in <module>
    from django.contrib.auth.forms import (
  File "/Users/paul/myapp/.direnv/python-3.8.5/lib/python3.8/site-packages/django/contrib/auth/forms.py", line 21, in <module>
    UserModel = get_user_model()
  File "/Users/paul/myapp/.direnv/python-3.8.5/lib/python3.8/site-packages/django/contrib/auth/__init__.py", line 161, in get_user_model
    raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'myapp.CustomUser' that has not been installed

settings.py ,我有

AUTH_USER_MODEL = 'myapp.CustomUser'

如果我注釋掉該行,服務器將啟動,但頁面加載失敗:

ValueError: Cannot create form field for 'user' yet, because its related model
'CustomUser' has not been loaded yet

這似乎與問題 62394664相同的崩潰。

好像您忘記遷移數據庫了。 試試這個命令python manage.py makemigrations python manage.py migrate

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM