Django - 如何在构造函数中运行函数?

时间:2017-11-24 10:58:14

标签: python django python-3.x django-models constructor

据我所知,不建议在Django中覆盖 init 功能。然后,我如何将值分配给"散列"和"盐"?它们不具有原始文本的值,有名为def createSalt(self):def createHash(self, salt, password):的函数将采用原始文本并将其转换为不同的文本。我在模型课中尝试了这个但是它没有工作:(它可能看起来很愚蠢)

salt = models.TextField(createSalt()) 

salt = models.TextField(createSalt(self))

另一个建议是定义一个名为create的新函数,并将其用作构造函数。但那它不是一个真正的构造函数,是吗?

这是我的模特:

class User(models.Model):
        username = models.CharField(db.String(100), primary_key=True)
        hashed = models.TextField()
        salt = models.TextField()

1 个答案:

答案 0 :(得分:0)

不确定你能以此为例吗?

import uuid

...

uuid = models.UUIDField(unique=True, default=uuid.uuid1, null=True, blank=True)

这里的uuid.uuid1只是一个方法,而不是。

def uuid1(node=None, clock_seq=None):
    """Generate a UUID from a host ID, sequence number, and the current time.
    If 'node' is not given, getnode() is used to obtain the hardware
    address.  If 'clock_seq' is given, it is used as the sequence number;
    otherwise a random 14-bit sequence number is chosen."""

    # When the system provides a version-1 UUID generator, use it (but don't
    # use UuidCreate here because its UUIDs don't conform to RFC 4122).
    if _uuid_generate_time and node is clock_seq is None:
        _buffer = ctypes.create_string_buffer(16)
        _uuid_generate_time(_buffer)
        return UUID(bytes=bytes_(_buffer.raw))

    global _last_timestamp
    import time
    nanoseconds = int(time.time() * 1e9)
    # 0x01b21dd213814000 is the number of 100-ns intervals between the
    # UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00.
    timestamp = int(nanoseconds/100) + 0x01b21dd213814000
    if _last_timestamp is not None and timestamp <= _last_timestamp:
        timestamp = _last_timestamp + 1
    _last_timestamp = timestamp
    if clock_seq is None:
        import random
        clock_seq = random.randrange(1<<14) # instead of stable storage
    time_low = timestamp & 0xffffffff
    time_mid = (timestamp >> 32) & 0xffff
    time_hi_version = (timestamp >> 48) & 0x0fff
    clock_seq_low = clock_seq & 0xff
    clock_seq_hi_variant = (clock_seq >> 8) & 0x3f
    if node is None:
        node = getnode()
    return UUID(fields=(time_low, time_mid, time_hi_version,
                        clock_seq_hi_variant, clock_seq_low, node), version=1)