以下是我尝试实施的身份验证模型:
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import BaseUserManager
# Create your models here.
class AccountManager(BaseUserManager):
def create_user(self, username=None, password=None, **kwargs):
account = self.model(username=username)
account.set_password(password)
account.save()
return account
def create_superuser(self, username, password, **kwargs):
account = self.create_superuser(username, password, **kwargs)
account.is_admin = True
account.save()
return account
class Account(AbstractBaseUser):
username = models.CharField(max_length=40, unique=True)
is_admin = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
USERNAME_FIELD = 'username'
objects = AccountManager()
当我从终端运行createsuperuser
命令时,它会抛出此错误
...................
File "../models.py", line 22, in create_superuser
account = self.create_superuser(username, password, **kwargs)
File "../models.py", line 22, in create_superuser
account = self.create_superuser(username, password, **kwargs)
RuntimeError: maximum recursion depth exceeded while calling a Python object
答案 0 :(得分:1)
create_superuser
上的AccountManager
方法调用自身会导致无限递归,因为Python具有最大递归深度,无限递归在到达时会被异常停止。
您可能想要做的是:
def create_superuser(self, username, password, **kwargs):
account = self.create_user(username, password, **kwargs)
account.is_admin = True
account.save()
return account