我在管理面板中的用户中尝试添加用户时遇到了这个 FieldError。当我单击添加用户时,会弹出此错误。我从未在代码的任何地方使用过 usable_password,并尝试了多种方法来解决此问题,方法是删除 db.sqlite3、迁移,然后重新执行 makemirations。还有一件事是我更改了 models.py 中类的拼写(执行迁移后再次执行迁移,成功创建了迁移文件)。我想了解为什么会发生这种情况,还有一件事,不久前我在另一个项目中遇到过类似的错误,我不知道那次是如何解决的。
FieldError at /admin/accounts/customuser/add/ Unknown field(s) (usable_password) specified for CustomUser. Check fields/fieldsets/exclude attributes of class CustomUserAdmin. Request Method: GET Request URL: http://127.0.0.1:8000/admin/accounts/customuser/add/ Django Version: 5.1.4 Exception Type: FieldError Exception Value: Unknown field(s) (usable_password) specified for CustomUser. Check fields/fieldsets/exclude attributes of class CustomUserAdmin. Exception Location: C:\Users\Learning Django\blog-api\.venv\Lib\site-packages\django\contrib\admin\options.py, line 841, in get_form Raised during: django.contrib.auth.admin.add_view Python Executable: C:\Users\Learning Django\blog-api\.venv\Scripts\python.exe Python Version: 3.12.2 Python Path: ['C:\\Users\\Desktop\\Learning ' 'Django\\blog-api\\django_project', 'C:\\Python312\\python312.zip', 'C:\\Python312\\DLLs', 'C:\\Python312\\Lib', 'C:\\Python312', 'C:\\Users\\Learning ' 'Django\\blog-api\\.venv', 'C:\\Users\\Learning ' 'Django\\blog-api\\.venv\\Lib\\site-packages']
我附上了 models.py、forms.py 和 admin.py 的代码:models.py
from django.db import models
# Create your models here.
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
name = models.CharField(null = True, blank = True, max_length = 255)
表单.py
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm):
model = CustomUser
fields = UserCreationForm.Meta.fields + ('name',)
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = CustomUser
fields = UserChangeForm.Meta.fields
管理工具
from django.contrib import admin
# Register your models here.
from django.contrib.auth.admin import UserAdmin
from .forms import CustomUserCreationForm, CustomUserChangeForm
from .models import CustomUser
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
change = CustomUserChangeForm
model = CustomUser
list_display = [
"email",
"username",
"name",
"is_staff",
]
fieldsets = UserAdmin.fieldsets + ((None, {"fields": ("name",)}),)
add_fieldsets = UserAdmin.add_fieldsets + ((None, {"fields": ("name",)}),)
admin.site.register(CustomUser, CustomUserAdmin)
Django 分别使用
AdminUserCreationForm
和AdminPasswordChangeForm
表示add_form
和change_password_form
。这些表单允许将密码设置为不可用。例如,这样做是为了防止用户使用密码登录(但例如使用 OTP 或通过其他方式)。
因此,您可以混合使用以下形式
UserAdmin
: