github.com/tmlbl/deis@v1.0.2/controller/api/fields.py (about)

     1  """
     2  Deis API custom fields for representing data in Django forms.
     3  """
     4  
     5  from __future__ import unicode_literals
     6  from uuid import uuid4
     7  
     8  from django import forms
     9  from django.db import models
    10  
    11  
    12  class UuidField(models.CharField):
    13      """A univerally unique ID field."""
    14  
    15      description = __doc__
    16  
    17      def __init__(self, *args, **kwargs):
    18          kwargs.setdefault('auto_created', True)
    19          kwargs.setdefault('editable', False)
    20          kwargs.setdefault('max_length', 32)
    21          kwargs.setdefault('unique', True)
    22          super(UuidField, self).__init__(*args, **kwargs)
    23  
    24      def db_type(self, connection=None):
    25          """Return the database column type for a UuidField."""
    26          if connection and 'postgres' in connection.vendor:
    27              return 'uuid'
    28          else:
    29              return "char({})".format(self.max_length)
    30  
    31      def pre_save(self, model_instance, add):
    32          """Initialize an empty field with a new UUID before it is saved."""
    33          value = getattr(model_instance, self.get_attname(), None)
    34          if not value and add:
    35              uuid = str(uuid4())
    36              setattr(model_instance, self.get_attname(), uuid)
    37              return uuid
    38          else:
    39              return super(UuidField, self).pre_save(model_instance, add)
    40  
    41      def formfield(self, **kwargs):
    42          """Tell forms how to represent this UuidField."""
    43          kwargs.update({
    44              'form_class': forms.CharField,
    45              'max_length': self.max_length,
    46          })
    47          return super(UuidField, self).formfield(**kwargs)
    48  
    49  
    50  try:
    51      from south.modelsinspector import add_introspection_rules
    52      # Tell the South schema migration tool to handle our custom fields.
    53      add_introspection_rules([], [r'^api\.fields\.UuidField'])
    54  except ImportError:  # pragma: no cover
    55      pass