Django Runtime Error: calling method in __init__ causes maximum recursion depth exceeded

Django Runtime Error: calling method in __init__ causes maximum recursion depth exceeded

我想在实例化 Register class 时调用 password_generator 方法,并将方法中的值 return 赋给 password 字段。

注册对象实例化时,为什么会得到

RuntimeError at /register/

maximum recursion depth exceeded while calling a Python object

这是代码

models.py

class Register(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    email = models.EmailField(max_length=120, blank=False, null=False)
    password = models.TextField(blank=False, null=False)
    firstname= models.CharField(max_length=120, blank=False, null=False)
    lastname = models.CharField(max_length=120, blank=False, null=False)
    phonenumber = models.CharField(max_length=120, blank=True, null=True)

    def __init__(self, *args, **kwargs):
        self.password = Register().password_generator()

    #Generate random login password for candidate
    def password_generator(self, size=30, chars=string.ascii_letters + string.digits + string.punctuation):
        return ''.join(random.choice(chars) for i in range(size))

来自终端的日志

控制台

  File "D:\Project\Online-Examination-System\register\models.py", line 31, in __init__
    self.password = Register().password_generator()
  File "D:\Project\Online-Examination-System\register\models.py", line 31, in __init__
    self.password = Register().password_generator()
  File "D:\Project\Online-Examination-System\register\models.py", line 31, in __init__
    self.password = Register().password_generator()
  File "D:\Project\Online-Examination-System\register\models.py", line 31, in __init__
    self.password = Register().password_generator()
  File "D:\Project\Online-Examination-System\register\models.py", line 31, in __init__
    self.password = Register().password_generator()
  File "D:\Project\Online-Examination-System\register\models.py", line 31, in __init__
    self.password = Register().password_generator()
  File "D:\Project\Online-Examination-System\register\models.py", line 31, in __init__
    self.password = Register().password_generator()
  File "D:\Project\Online-Examination-System\register\models.py", line 31, in __init__
    self.password = Register().password_generator()
  File "D:\Project\Online-Examination-System\register\models.py", line 31, in __init__
    self.password = Register().password_generator()

如何解决这个问题?

经过多次尝试,我开始意识到我要调用的函数处于无限循环中。要访问 password_generator() 方法,我必须执行 Register().password_generator()。所以这也意味着 __init__ 方法被调用——因为 Register()。在__init()__,我再次调用Register()。这就是它变成无限循环的原因。为了解决这个问题,我们必须使用:

    def __init__(self, *args, **kwargs):
    self.password = self.password_generator()