class Foo(models.Model): secret = models.CharField(max_length=12, blank=True, editable=False) def generateSecret(self): s = struct.pack('L', random.getrandbits(32)) s += struct.pack('L', random.getrandbits(32)) s += struct.pack('L', random.getrandbits(8)) self.secret = base64.urlsafe_b64encode(s[0:9]) self.save()