Login

autogenerated UUID model field

Author:
kedar
Posted:
March 6, 2014
Language:
Python
Version:
Not specified
Score:
0 (after 0 ratings)

Provides UUIDField for your models. This version creates very short UUID represenation (21 chars) when the record is added eg. in admin. Generated ids are safe to be used in URLs.

You can put represent it in admin as

'readonly_fields=("uuid",)'

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# in file field.py
# adjust add_introspection_rules line as needed

from django.conf import settings

from django.db.models import CharField
import uuid

class UUIDField(CharField) :
    """
    UUIDField stored in 21 Chars
    Example: uuid = UUIDField(editable=False)
    """     
    def __init__(self, *args, **kwargs):
        kwargs['max_length'] = kwargs.get('max_length', 22 )
        # kwargs['blank'] = True
        kwargs['default'] = lambda: uuid.uuid4().bytes.encode('base64').rstrip('=\n').replace('/', '_')
        CharField.__init__(self, *args, **kwargs)
    
###################            
    
# South requires custom fields to be given "rules".
# See http://south.aeracode.org/docs/customfields.html
if "south" in settings.INSTALLED_APPS:
    try:
        from south.modelsinspector import add_introspection_rules
        add_introspection_rules([], ["extend\.fields\.UUIDField"])
    except ImportError:
        pass

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 8 months ago

Comments

Please login first before commenting.