Debian Codegraph @

shortuuidfield/fields.py

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 import shortuuid
2 import six
3 import sys
4 from django.db.models import CharField
5
6
7 class ShortUUIDField(CharField):
8 """
9 A field which stores a Short UUID value in base57 format. This may also have
10 the Boolean attribute 'auto' which will set the value on initial save to a
11 new UUID value (calculated using shortuuid's default (uuid4)). Note that while all
12 UUIDs are expected to be unique we enforce this with a DB constraint.
13 """
14
15 def __init__(self, auto=True, *args, **kwargs):
16 self.auto = auto
17 # We store UUIDs in base57 format, which is fixed at 22 characters.
18 kwargs['max_length'] = 22
19 if auto:
20 # Do not let the user edit UUIDs if they are auto-assigned.
21 kwargs['editable'] = False
22 kwargs['blank'] = True
23 # kwargs['unique'] = True # if you want to be paranoid, set unique=True in your instantiation of the field.
24
25 super(ShortUUIDField, self).__init__(*args, **kwargs)
26
27 def pre_save(self, model_instance, add):
28 """
29 This is used to ensure that we auto-set values if required.
30 See CharField.pre_save
31 """
32 value = super(ShortUUIDField, self).pre_save(model_instance, add)
33 if self.auto and not value:
34 # Assign a new value for this attribute if required.
35 value = six.text_type(shortuuid.uuid())
36 setattr(model_instance, self.attname, value)
37 return value
38
39 def formfield(self, **kwargs):
40 if self.auto:
41 return None
42 return super(ShortUUIDField, self).formfield(**kwargs)
43
44 try:
45 from south.modelsinspector import add_introspection_rules
46 add_introspection_rules([], [r"^shortuuidfield\.fields\.ShortUUIDField"])
47 except ImportError:
48 pass