🚀

DjangoでIDをEmailにしてAdminでサインアップ時IDが空欄になる問題

2024/11/26に公開

カスタムモデルを作ってEmailログインにした。
Emailログインにした時にEmailは必須。しかし、Django adminから作ると空欄で作られてしまう。

前提

models.py
class UserAccount(AbstractBaseUser, PermissionsMixin):
    ...
    email = models.EmailField(
        max_length=20, null=False, unique=True, verbose_name=_("Email")
    )
    EMAIL_FIELD = "email"
    USERNAME_FIELD = "email"

解決策

admin.py
 @admin.register(UserAccount)
 class UserAccountAdmin(UserAdmin):
     model = UserAccount
     list_per_page = 15
     # exclude = ("password",)
     add_fieldsets = (
         (
             None,
             {
                 "classes": ("wide",),
-                "fields": ("username", "password1", "password2"),
+                "fields": ("email", "username", "password1", "password2"),
             },
         ),
     )
     fieldsets = (
         (None, {"fields": ("username", "password")}),
         (_("Personal info"), {"fields": ("email",)}),
         (
             _("Permissions"),
             {
                 "fields": (
                     "is_active",
                     "is_verified_email",
                     "is_staff",
                     "is_superuser",
                     "groups",
                     "user_permissions",
                 ),
             },
         ),
         (_("Important dates"), {"fields": ("last_login", "date_joined")}),
     )
     list_display = (
         "email",
         "username",
         "is_staff",
         "is_superuser",
         "is_verified_email",
         "is_active",
     )

Discussion