覆盖模型保存方法不允许分配值

时间:2019-05-26 14:41:41

标签: django

我试图覆盖模型的保存方法,并在保存字段时为该字段分配一个值:

我的模型。py:

def NewInviteCode():
    import secrets
    print(secrets.token_urlsafe(16))


class Invitation(models.Model):
    id = models.AutoField(primary_key=True, unique=True)
    name = models.CharField(max_length=300, default='', blank=True)
    email = models.EmailField(max_length=100, default='')
    mobile = models.CharField(max_length=15, default='', blank=True)
    last_sent = models.DateTimeField(default=timezone.now)
    num_invitations = models.IntegerField(default=1)
    uniqcode = models.CharField(max_length=300, default='', blank=True)

    def save(self, *args, **kwargs):
        if not self.uniqcode:
            self.uniqcode = NewInviteCode()
            print(f"Saved new unique code: {self.uniqcode}")
        if self.num_invitations:
            self.num_invitations = self.num_invitations + 1
        print(f"Sending invitation to {self.email}..")
        SendInviteActual(self.email)
        print(f"Parameters to be saved are: Code:{self.uniqcode} Name: {self.name} Email: {self.email}")
        super().save(*args, **kwargs)  # Call the "real" save() method.

不幸的是,在我的代码执行中:

fktewVPm63tV-YqXxWPNxQ
Saved new unique code: None
Sending invitation to joel@domain.com.
Mail sent
Parameters to be saved are: Code:None Name: joel Email: joel@domain.com
2019-05-26 20:04:48,972 django.request ERROR    Internal Server Error: /clinic/sendinvites

以下几行代码有什么问题?

if not self.uniqcode:
    self.uniqcode = NewInviteCode()
    print(f"Saved new unique code: {self.uniqcode}")

1 个答案:

答案 0 :(得分:1)

您的NewInviteCode不会返回任何东西,它只会 print 个东西。如果Python函数未明确返回内容,则返回None。您应该返回一个值,例如:

def NewInviteCode():
    from secrets import token_urlsafe
    return token_urlsafe(16)

话虽如此,您可以将字段的可调用对象设置为default= parameter [Django-doc],例如:

def new_invite_code():
    from secrets import token_urlsafe
    return token_urlsafe(16)

class Invitation(models.Model):
    id = models.AutoField(primary_key=True, unique=True)
    name = models.CharField(max_length=300, default='', blank=True)
    email = models.EmailField(max_length=100, default='')
    mobile = models.CharField(max_length=15, default='', blank=True)
    last_sent = models.DateTimeField(default=timezone.now)
    num_invitations = models.IntegerField(default=1)
    uniqcode = models.CharField(max_length=300, default=new_invite_code, blank=True)

因此我们在这里调用我们传递的new_invite_code函数,而不是new_invite_code的结果,因此我们 not 写括号(例如 {new_invite_code() )。

这使您的模型和safe(..)功能更简单。

  

注意:根据PEP-8 style guide,您应该像在第二个代码片段中一样将NewInviteCode重命名为new_invite_code