填充Django模型字段

时间:2013-04-26 07:51:05

标签: django

我是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)

1 个答案:

答案 0 :(得分: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/