0

我是 django 新手,我创建了一个如下模型。我希望在从管理面板创建新的 Apiuser 时自动填充这些 api_key 和 secret_key。

生成 api_key 和 secret_key 的逻辑

".join([random.choice(string.letters + string.digits + string.punctuation) for _ in xrange(64)])

这是模型:

class ApiUser(models.Model):
    name = models.CharField(max_length = 50)
    email = models.EmailField()
    api_key = RandomAlphaNum(editable=False)
    secret_key = RandomAlphaNum(editable=False)
    quota = models.IntegerField()
    used = models.IntegerField()
    datejoined = models.DateTimeField(auto_now_add = True)
    status = models.CharField(max_length=1, choices=STATUS_CHOICES)
4

1 回答 1

3

您可以使用post_save信号,例如

from django.db.models.signals import post_save
from django.dispatch import receiver
from myapp.models import MyModel

@receiver(post_save, sender=MyModel)
def my_handler(sender, **kwargs):
    # do stuff

更多关于信号:https ://docs.djangoproject.com/en/dev/topics/signals/

于 2013-04-26T07:58:35.310 回答