Debian Codegraph @

shortuuidfield/fields.py

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