|
| 1 | +from django.core import exceptions, validators |
| 2 | +from django.db.models import fields |
| 3 | +from django.template.defaultfilters import slugify |
| 4 | +from django.db import models |
| 5 | +from django.core.serializers.json import DjangoJSONEncoder |
| 6 | +from django.utils import simplejson as json |
| 7 | + |
| 8 | +from south.modelsinspector import add_introspection_rules |
| 9 | +from django_common.helper import md5_hash |
| 10 | + |
| 11 | + |
| 12 | +class JSONField(models.TextField): |
| 13 | + """ |
| 14 | + JSONField is a generic textfield that neatly serializes/unserializes JSON objects seamlessly |
| 15 | + """ |
| 16 | + |
| 17 | + # Used so to_python() is called |
| 18 | + __metaclass__ = models.SubfieldBase |
| 19 | + |
| 20 | + def to_python(self, value): |
| 21 | + """Convert our string value to JSON after we load it from the DB""" |
| 22 | + |
| 23 | + if value == "": |
| 24 | + return None |
| 25 | + |
| 26 | + try: |
| 27 | + if isinstance(value, basestring): |
| 28 | + return json.loads(value) |
| 29 | + except ValueError: |
| 30 | + pass |
| 31 | + |
| 32 | + return value |
| 33 | + |
| 34 | + def get_db_prep_save(self, value): |
| 35 | + """Convert our JSON object to a string before we save""" |
| 36 | + |
| 37 | + if value == "": |
| 38 | + return None |
| 39 | + |
| 40 | + if isinstance(value, dict): |
| 41 | + value = json.dumps(value, cls=DjangoJSONEncoder) |
| 42 | + |
| 43 | + return super(JSONField, self).get_db_prep_save(value) |
| 44 | + |
| 45 | +class UniqueSlugField(fields.SlugField): |
| 46 | + """ |
| 47 | + Represents a self-managing sluf field, that makes sure that the slug value is unique on the db table. Slugs by |
| 48 | + default get a db_index on them. The "Unique" in the class name is a misnomer since it does support unique=False |
| 49 | + |
| 50 | + @requires "prepopulate_from" in the constructor. This could be a field or a function in the model class which is using |
| 51 | + this field |
| 52 | + |
| 53 | + Defaults update_on_save to False |
| 54 | + |
| 55 | + Taken and edited from: http://www.djangosnippets.org/snippets/728/ |
| 56 | + """ |
| 57 | + def __init__(self, prepopulate_from='id', *args, **kwargs): |
| 58 | + if kwargs.get('update_on_save'): |
| 59 | + self.__update_on_save = kwargs.pop('update_on_save') |
| 60 | + else: |
| 61 | + self.__update_on_save = False |
| 62 | + self.prepopulate_from = prepopulate_from |
| 63 | + super(UniqueSlugField, self).__init__(*args, **kwargs) |
| 64 | + |
| 65 | + def pre_save(self, model_instance, add): |
| 66 | + prepopulate_field = getattr(model_instance, self.prepopulate_from) |
| 67 | + if callable(prepopulate_field): |
| 68 | + prepopulate_value = prepopulate_field() |
| 69 | + else: |
| 70 | + prepopulate_value = prepopulate_field |
| 71 | + |
| 72 | + # if object has an id, and not to update on save, then return existig model instance's slug value |
| 73 | + if getattr(model_instance, 'id') and not self.__update_on_save: |
| 74 | + return getattr(model_instance, self.name) |
| 75 | + |
| 76 | + # if this is a previously saved object, and current instance's slug is same as one being proposed |
| 77 | + if getattr(model_instance, 'id') and getattr(model_instance, self.name) == prepopulate_value: |
| 78 | + return self.__set_and_return(model_instance, self.name, slugify(prepopulate_value)) |
| 79 | + |
| 80 | + # if a unique slug is not required (not the default of course) |
| 81 | + if not self.unique: |
| 82 | + return self.__set_and_return(model_instance, self.name, slugify(prepopulate_value)) |
| 83 | + |
| 84 | + return self.__unique_slug(model_instance.__class__, model_instance, self.name, |
| 85 | + prepopulate_value) |
| 86 | + |
| 87 | + def __unique_slug(self, model, model_instance, slug_field, slug_value): |
| 88 | + orig_slug = slug = slugify(slug_value) |
| 89 | + index = 1 |
| 90 | + while True: |
| 91 | + try: |
| 92 | + model.objects.get(**{slug_field: slug}) |
| 93 | + index += 1 |
| 94 | + slug = orig_slug + '-' + str(index) |
| 95 | + except model.DoesNotExist: |
| 96 | + return self.__set_and_return(model_instance, slug_field, slug) |
| 97 | + |
| 98 | + def __set_and_return(self, model_instance, slug_field, slug): |
| 99 | + setattr(model_instance, slug_field, slug) |
| 100 | + return slug |
| 101 | + |
| 102 | +add_introspection_rules([ |
| 103 | + ( |
| 104 | + [UniqueSlugField], # Class(es) these apply to |
| 105 | + [], # Positional arguments (not used) |
| 106 | + { # Keyword argument |
| 107 | + "prepopulate_from": ["prepopulate_from", {"default": 'id'}], |
| 108 | + }, |
| 109 | + ), |
| 110 | +], ["^django_common\.db_fields\.UniqueSlugField"]) |
| 111 | + |
| 112 | + |
| 113 | +class RandomHashField(fields.CharField): |
| 114 | + """ |
| 115 | + Store a random hash for a certain model field. |
| 116 | + |
| 117 | + @param update_on_save optional field whether to update this hash or not, everytime the model instance is saved |
| 118 | + """ |
| 119 | + def __init__(self, update_on_save=False, *args, **kwargs): |
| 120 | + #TODO: args & kwargs serve no purpose but to make django evolution to work |
| 121 | + self.update_on_save = update_on_save |
| 122 | + super(fields.CharField, self).__init__(max_length=128, unique=True, blank=False, null=False, db_index=True, default=md5_hash()) |
| 123 | + |
| 124 | + def pre_save(self, model_instance, add): |
| 125 | + if not add and not self.update_on_save: |
| 126 | + return getattr(model_instance, self.name) |
| 127 | + |
| 128 | + random_hash = md5_hash() |
| 129 | + setattr(model_instance, self.name, random_hash) |
| 130 | + return random_hash |
| 131 | + |
| 132 | +add_introspection_rules([ |
| 133 | + ( |
| 134 | + [RandomHashField], # Class(es) these apply to |
| 135 | + [], # Positional arguments (not used) |
| 136 | + { # Keyword argument |
| 137 | + "update_on_save": ["update_on_save", {"default": False}], |
| 138 | + }, |
| 139 | + ), |
| 140 | +], ["^django_common\.db_fields\.RandomHashField"]) |
0 commit comments