2021-03-10 09:06:34 +00:00
|
|
|
import secrets
|
2019-02-26 16:50:32 +00:00
|
|
|
import uuid
|
2020-11-29 20:58:00 +00:00
|
|
|
|
2010-01-15 22:26:59 +00:00
|
|
|
from django.conf import settings
|
2019-02-26 18:17:06 +00:00
|
|
|
from django.core.exceptions import ValidationError
|
2020-11-29 20:58:00 +00:00
|
|
|
from django.db import models
|
2013-04-12 23:12:06 +00:00
|
|
|
from django.utils.timezone import now
|
2012-01-07 22:43:39 +00:00
|
|
|
|
2013-11-14 19:12:31 +00:00
|
|
|
DEFAULT_CHOICES_NAME = 'STATUS'
|
|
|
|
|
|
2012-01-07 22:43:39 +00:00
|
|
|
|
2010-04-15 02:43:27 +00:00
|
|
|
class AutoCreatedField(models.DateTimeField):
|
2009-07-02 20:14:29 +00:00
|
|
|
"""
|
|
|
|
|
A DateTimeField that automatically populates itself at
|
|
|
|
|
object creation.
|
|
|
|
|
|
|
|
|
|
By default, sets editable=False, default=datetime.now.
|
|
|
|
|
|
|
|
|
|
"""
|
2019-02-26 16:33:06 +00:00
|
|
|
|
2010-04-15 02:43:27 +00:00
|
|
|
def __init__(self, *args, **kwargs):
|
2009-07-02 20:14:29 +00:00
|
|
|
kwargs.setdefault('editable', False)
|
2012-01-07 22:43:39 +00:00
|
|
|
kwargs.setdefault('default', now)
|
2019-11-14 16:50:04 +00:00
|
|
|
super().__init__(*args, **kwargs)
|
2009-07-02 20:14:29 +00:00
|
|
|
|
2010-04-15 02:53:55 +00:00
|
|
|
|
2010-04-15 02:43:27 +00:00
|
|
|
class AutoLastModifiedField(AutoCreatedField):
|
2009-07-02 20:14:29 +00:00
|
|
|
"""
|
|
|
|
|
A DateTimeField that updates itself on each save() of the model.
|
|
|
|
|
|
|
|
|
|
By default, sets editable=False and default=datetime.now.
|
2011-04-29 01:59:52 +00:00
|
|
|
|
2009-07-02 20:14:29 +00:00
|
|
|
"""
|
2019-08-20 11:11:26 +00:00
|
|
|
def get_default(self):
|
|
|
|
|
"""Return the default value for this field."""
|
|
|
|
|
if not hasattr(self, "_default"):
|
2024-06-11 17:46:51 +00:00
|
|
|
self._default = super().get_default()
|
2019-08-20 11:11:26 +00:00
|
|
|
return self._default
|
2019-02-26 16:33:06 +00:00
|
|
|
|
2010-04-15 02:43:27 +00:00
|
|
|
def pre_save(self, model_instance, add):
|
2012-01-07 22:43:39 +00:00
|
|
|
value = now()
|
2019-08-20 11:11:26 +00:00
|
|
|
if add:
|
|
|
|
|
current_value = getattr(model_instance, self.attname, self.get_default())
|
|
|
|
|
if current_value != self.get_default():
|
|
|
|
|
# when creating an instance and the modified date is set
|
|
|
|
|
# don't change the value, assume the developer wants that
|
|
|
|
|
# control.
|
|
|
|
|
value = getattr(model_instance, self.attname)
|
|
|
|
|
else:
|
|
|
|
|
for field in model_instance._meta.get_fields():
|
|
|
|
|
if isinstance(field, AutoCreatedField):
|
|
|
|
|
value = getattr(model_instance, field.name)
|
|
|
|
|
break
|
2009-07-02 20:14:29 +00:00
|
|
|
setattr(model_instance, self.attname, value)
|
2010-04-15 02:43:27 +00:00
|
|
|
return value
|
2010-01-15 22:26:59 +00:00
|
|
|
|
2010-04-15 02:53:55 +00:00
|
|
|
|
2010-04-15 18:00:44 +00:00
|
|
|
class StatusField(models.CharField):
|
2010-04-15 02:53:55 +00:00
|
|
|
"""
|
2010-04-16 03:47:28 +00:00
|
|
|
A CharField that looks for a ``STATUS`` class-attribute and
|
|
|
|
|
automatically uses that as ``choices``. The first option in
|
|
|
|
|
``STATUS`` is set as the default.
|
|
|
|
|
|
|
|
|
|
Also has a default max_length so you don't have to worry about
|
|
|
|
|
setting that.
|
2010-04-15 02:53:55 +00:00
|
|
|
|
2010-04-23 10:47:38 +00:00
|
|
|
Also features a ``no_check_for_status`` argument to make sure
|
2010-04-23 10:44:59 +00:00
|
|
|
South can handle this field when it freezes a model.
|
2010-04-15 02:53:55 +00:00
|
|
|
"""
|
2019-02-26 16:33:06 +00:00
|
|
|
|
2023-03-20 16:47:13 +00:00
|
|
|
def __init__(self, *args, no_check_for_status=False, choices_name=DEFAULT_CHOICES_NAME, **kwargs):
|
2010-04-15 18:00:44 +00:00
|
|
|
kwargs.setdefault('max_length', 100)
|
2023-03-20 16:47:13 +00:00
|
|
|
self.check_for_status = not no_check_for_status
|
|
|
|
|
self.choices_name = choices_name
|
2019-11-14 16:50:04 +00:00
|
|
|
super().__init__(*args, **kwargs)
|
2010-04-15 18:00:44 +00:00
|
|
|
|
2013-04-09 21:28:53 +00:00
|
|
|
def prepare_class(self, sender, **kwargs):
|
|
|
|
|
if not sender._meta.abstract and self.check_for_status:
|
2013-11-14 19:12:31 +00:00
|
|
|
assert hasattr(sender, self.choices_name), \
|
|
|
|
|
"To use StatusField, the model '%s' must have a %s choices class attribute." \
|
|
|
|
|
% (sender.__name__, self.choices_name)
|
2019-08-21 09:02:23 +00:00
|
|
|
self.choices = getattr(sender, self.choices_name)
|
2013-02-21 20:08:15 +00:00
|
|
|
if not self.has_default():
|
2013-11-14 19:12:31 +00:00
|
|
|
self.default = tuple(getattr(sender, self.choices_name))[0][0] # set first as default
|
2013-04-09 21:28:53 +00:00
|
|
|
|
2024-04-03 06:53:52 +00:00
|
|
|
def contribute_to_class(self, cls, name, *args, **kwargs):
|
2013-04-09 21:28:53 +00:00
|
|
|
models.signals.class_prepared.connect(self.prepare_class, sender=cls)
|
2013-05-02 17:33:48 +00:00
|
|
|
# we don't set the real choices until class_prepared (so we can rely on
|
|
|
|
|
# the STATUS class attr being available), but we need to set some dummy
|
|
|
|
|
# choices now so the super method will add the get_FOO_display method
|
2019-08-21 09:02:23 +00:00
|
|
|
self.choices = [(0, 'dummy')]
|
2024-04-03 06:53:52 +00:00
|
|
|
super().contribute_to_class(cls, name, *args, **kwargs)
|
2010-04-15 02:53:55 +00:00
|
|
|
|
2014-04-25 20:32:49 +00:00
|
|
|
def deconstruct(self):
|
2019-11-14 16:50:04 +00:00
|
|
|
name, path, args, kwargs = super().deconstruct()
|
2014-04-25 21:17:42 +00:00
|
|
|
kwargs['no_check_for_status'] = True
|
2014-04-25 20:32:49 +00:00
|
|
|
return name, path, args, kwargs
|
|
|
|
|
|
2010-04-15 02:53:55 +00:00
|
|
|
|
2010-04-16 03:47:28 +00:00
|
|
|
class MonitorField(models.DateTimeField):
|
|
|
|
|
"""
|
|
|
|
|
A DateTimeField that monitors another field on the same model and
|
|
|
|
|
sets itself to the current date/time whenever the monitored field
|
|
|
|
|
changes.
|
2011-04-29 01:59:52 +00:00
|
|
|
|
2010-04-16 03:47:28 +00:00
|
|
|
"""
|
2019-02-26 16:33:06 +00:00
|
|
|
|
2023-03-20 16:47:13 +00:00
|
|
|
def __init__(self, *args, monitor, when=None, **kwargs):
|
2024-04-04 08:26:17 +00:00
|
|
|
default = None if kwargs.get("null") else now
|
|
|
|
|
kwargs.setdefault('default', default)
|
2010-04-16 03:47:28 +00:00
|
|
|
self.monitor = monitor
|
2013-10-11 11:24:00 +00:00
|
|
|
if when is not None:
|
|
|
|
|
when = set(when)
|
2013-10-11 03:08:38 +00:00
|
|
|
self.when = when
|
2019-11-14 16:50:04 +00:00
|
|
|
super().__init__(*args, **kwargs)
|
2010-04-15 02:53:55 +00:00
|
|
|
|
2024-04-03 06:53:52 +00:00
|
|
|
def contribute_to_class(self, cls, name, *args, **kwargs):
|
2010-04-16 03:47:28 +00:00
|
|
|
self.monitor_attname = '_monitor_%s' % name
|
|
|
|
|
models.signals.post_init.connect(self._save_initial, sender=cls)
|
2024-04-03 06:53:52 +00:00
|
|
|
super().contribute_to_class(cls, name, *args, **kwargs)
|
2010-04-16 03:47:28 +00:00
|
|
|
|
|
|
|
|
def get_monitored_value(self, instance):
|
|
|
|
|
return getattr(instance, self.monitor)
|
2011-04-29 01:59:52 +00:00
|
|
|
|
2010-04-16 03:47:28 +00:00
|
|
|
def _save_initial(self, sender, instance, **kwargs):
|
2019-08-21 09:02:23 +00:00
|
|
|
if self.monitor in instance.get_deferred_fields():
|
2016-11-18 23:11:23 +00:00
|
|
|
# Fix related to issue #241 to avoid recursive error on double monitor fields
|
|
|
|
|
return
|
2019-08-21 09:02:23 +00:00
|
|
|
setattr(instance, self.monitor_attname, self.get_monitored_value(instance))
|
2010-04-15 02:53:55 +00:00
|
|
|
|
|
|
|
|
def pre_save(self, model_instance, add):
|
2012-01-07 22:43:39 +00:00
|
|
|
value = now()
|
2010-04-16 03:47:28 +00:00
|
|
|
previous = getattr(model_instance, self.monitor_attname, None)
|
|
|
|
|
current = self.get_monitored_value(model_instance)
|
|
|
|
|
if previous != current:
|
2013-10-11 11:24:00 +00:00
|
|
|
if self.when is None or current in self.when:
|
2013-10-11 03:08:38 +00:00
|
|
|
setattr(model_instance, self.attname, value)
|
|
|
|
|
self._save_initial(model_instance.__class__, model_instance)
|
2019-11-14 16:50:04 +00:00
|
|
|
return super().pre_save(model_instance, add)
|
2010-04-15 02:53:55 +00:00
|
|
|
|
2014-04-24 02:55:39 +00:00
|
|
|
def deconstruct(self):
|
2019-11-14 16:50:04 +00:00
|
|
|
name, path, args, kwargs = super().deconstruct()
|
2014-09-22 18:49:35 +00:00
|
|
|
kwargs['monitor'] = self.monitor
|
2014-04-24 02:55:39 +00:00
|
|
|
if self.when is not None:
|
|
|
|
|
kwargs['when'] = self.when
|
|
|
|
|
return name, path, args, kwargs
|
|
|
|
|
|
2010-04-15 02:53:55 +00:00
|
|
|
|
2010-01-15 22:26:59 +00:00
|
|
|
SPLIT_MARKER = getattr(settings, 'SPLIT_MARKER', '<!-- split -->')
|
|
|
|
|
|
|
|
|
|
# the number of paragraphs after which to split if no marker
|
|
|
|
|
SPLIT_DEFAULT_PARAGRAPHS = getattr(settings, 'SPLIT_DEFAULT_PARAGRAPHS', 2)
|
|
|
|
|
|
2019-02-26 16:33:06 +00:00
|
|
|
|
2019-02-26 18:17:06 +00:00
|
|
|
def _excerpt_field_name(name):
|
|
|
|
|
return '_%s_excerpt' % name
|
2010-01-15 22:26:59 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_excerpt(content):
|
|
|
|
|
excerpt = []
|
|
|
|
|
default_excerpt = []
|
|
|
|
|
paras_seen = 0
|
|
|
|
|
for line in content.splitlines():
|
|
|
|
|
if not line.strip():
|
|
|
|
|
paras_seen += 1
|
|
|
|
|
if paras_seen < SPLIT_DEFAULT_PARAGRAPHS:
|
|
|
|
|
default_excerpt.append(line)
|
|
|
|
|
if line.strip() == SPLIT_MARKER:
|
|
|
|
|
return '\n'.join(excerpt)
|
|
|
|
|
excerpt.append(line)
|
2011-04-29 01:59:52 +00:00
|
|
|
|
2010-01-15 22:26:59 +00:00
|
|
|
return '\n'.join(default_excerpt)
|
|
|
|
|
|
2018-07-02 19:20:38 +00:00
|
|
|
|
2019-09-30 08:08:52 +00:00
|
|
|
class SplitText:
|
2010-01-15 22:26:59 +00:00
|
|
|
def __init__(self, instance, field_name, excerpt_field_name):
|
|
|
|
|
# instead of storing actual values store a reference to the instance
|
|
|
|
|
# along with field names, this makes assignment possible
|
|
|
|
|
self.instance = instance
|
|
|
|
|
self.field_name = field_name
|
|
|
|
|
self.excerpt_field_name = excerpt_field_name
|
|
|
|
|
|
2018-07-02 19:20:38 +00:00
|
|
|
@property
|
|
|
|
|
def content(self):
|
2010-01-15 22:26:59 +00:00
|
|
|
return self.instance.__dict__[self.field_name]
|
2018-07-02 19:20:38 +00:00
|
|
|
|
|
|
|
|
@content.setter
|
|
|
|
|
def content(self, val):
|
2010-01-15 22:26:59 +00:00
|
|
|
setattr(self.instance, self.field_name, val)
|
|
|
|
|
|
2023-03-20 16:38:55 +00:00
|
|
|
@property
|
|
|
|
|
def excerpt(self):
|
2010-01-15 22:26:59 +00:00
|
|
|
return getattr(self.instance, self.excerpt_field_name)
|
|
|
|
|
|
2023-03-20 16:38:55 +00:00
|
|
|
@property
|
|
|
|
|
def has_more(self):
|
2010-01-28 04:37:31 +00:00
|
|
|
return self.excerpt.strip() != self.content.strip()
|
2011-04-29 01:59:52 +00:00
|
|
|
|
2013-04-06 22:55:42 +00:00
|
|
|
def __str__(self):
|
2010-01-15 22:26:59 +00:00
|
|
|
return self.content
|
|
|
|
|
|
2018-07-02 19:20:38 +00:00
|
|
|
|
2019-09-30 08:08:52 +00:00
|
|
|
class SplitDescriptor:
|
2010-01-15 22:26:59 +00:00
|
|
|
def __init__(self, field):
|
|
|
|
|
self.field = field
|
|
|
|
|
self.excerpt_field_name = _excerpt_field_name(self.field.name)
|
|
|
|
|
|
|
|
|
|
def __get__(self, instance, owner):
|
|
|
|
|
if instance is None:
|
|
|
|
|
raise AttributeError('Can only be accessed via an instance.')
|
|
|
|
|
return SplitText(instance, self.field.name, self.excerpt_field_name)
|
|
|
|
|
|
|
|
|
|
def __set__(self, obj, value):
|
|
|
|
|
if isinstance(value, SplitText):
|
|
|
|
|
obj.__dict__[self.field.name] = value.content
|
|
|
|
|
setattr(obj, self.excerpt_field_name, value.excerpt)
|
|
|
|
|
else:
|
|
|
|
|
obj.__dict__[self.field.name] = value
|
|
|
|
|
|
2018-07-02 19:20:38 +00:00
|
|
|
|
2010-01-15 22:26:59 +00:00
|
|
|
class SplitField(models.TextField):
|
2024-04-03 06:53:52 +00:00
|
|
|
def contribute_to_class(self, cls, name, *args, **kwargs):
|
2024-04-10 12:17:34 +00:00
|
|
|
if not cls._meta.abstract:
|
2010-01-31 15:54:36 +00:00
|
|
|
excerpt_field = models.TextField(editable=False)
|
|
|
|
|
cls.add_to_class(_excerpt_field_name(name), excerpt_field)
|
2024-04-03 06:53:52 +00:00
|
|
|
super().contribute_to_class(cls, name, *args, **kwargs)
|
2010-01-15 22:26:59 +00:00
|
|
|
setattr(cls, self.name, SplitDescriptor(self))
|
|
|
|
|
|
|
|
|
|
def pre_save(self, model_instance, add):
|
2019-11-14 16:50:04 +00:00
|
|
|
value = super().pre_save(model_instance, add)
|
2010-01-15 22:26:59 +00:00
|
|
|
excerpt = get_excerpt(value.content)
|
|
|
|
|
setattr(model_instance, _excerpt_field_name(self.attname), excerpt)
|
|
|
|
|
return value.content
|
|
|
|
|
|
|
|
|
|
def value_to_string(self, obj):
|
2016-03-27 00:43:30 +00:00
|
|
|
value = self.value_from_object(obj)
|
2010-01-15 22:26:59 +00:00
|
|
|
return value.content
|
|
|
|
|
|
2011-02-18 21:45:39 +00:00
|
|
|
def get_prep_value(self, value):
|
2010-01-15 22:26:59 +00:00
|
|
|
try:
|
|
|
|
|
return value.content
|
|
|
|
|
except AttributeError:
|
|
|
|
|
return value
|
|
|
|
|
|
2011-04-29 01:59:52 +00:00
|
|
|
|
2019-02-26 16:33:06 +00:00
|
|
|
class UUIDField(models.UUIDField):
|
|
|
|
|
"""
|
2019-02-26 17:38:39 +00:00
|
|
|
A field for storing universally unique identifiers. Use Python UUID class.
|
2019-02-26 16:33:06 +00:00
|
|
|
"""
|
2010-01-07 04:20:31 +00:00
|
|
|
|
2019-02-26 16:33:06 +00:00
|
|
|
def __init__(self, primary_key=True, version=4, editable=False, *args, **kwargs):
|
|
|
|
|
"""
|
|
|
|
|
Parameters
|
|
|
|
|
----------
|
|
|
|
|
primary_key : bool
|
|
|
|
|
If True, this field is the primary key for the model.
|
|
|
|
|
version : int
|
|
|
|
|
An integer that set default UUID version.
|
|
|
|
|
editable : bool
|
|
|
|
|
If False, the field will not be displayed in the admin or any other ModelForm,
|
|
|
|
|
default is false.
|
|
|
|
|
|
|
|
|
|
Raises
|
|
|
|
|
------
|
2019-02-26 18:17:06 +00:00
|
|
|
ValidationError
|
2019-02-26 16:33:06 +00:00
|
|
|
UUID version 2 is not supported.
|
|
|
|
|
"""
|
2019-08-19 21:38:05 +00:00
|
|
|
|
2019-02-27 01:29:47 +00:00
|
|
|
if version == 2:
|
2019-02-26 18:17:06 +00:00
|
|
|
raise ValidationError(
|
2019-02-26 18:01:39 +00:00
|
|
|
'UUID version 2 is not supported.')
|
2019-08-19 21:38:05 +00:00
|
|
|
|
2019-02-27 01:29:47 +00:00
|
|
|
if version < 1 or version > 5:
|
|
|
|
|
raise ValidationError(
|
|
|
|
|
'UUID version is not valid.')
|
2019-08-19 21:38:05 +00:00
|
|
|
|
2019-02-27 01:29:47 +00:00
|
|
|
if version == 1:
|
|
|
|
|
default = uuid.uuid1
|
2019-02-26 16:33:06 +00:00
|
|
|
elif version == 3:
|
|
|
|
|
default = uuid.uuid3
|
2019-02-27 01:29:47 +00:00
|
|
|
elif version == 4:
|
|
|
|
|
default = uuid.uuid4
|
2019-02-26 16:33:06 +00:00
|
|
|
elif version == 5:
|
2019-08-19 21:38:05 +00:00
|
|
|
default = uuid.uuid5
|
|
|
|
|
|
2019-02-27 01:29:47 +00:00
|
|
|
kwargs.setdefault('primary_key', primary_key)
|
|
|
|
|
kwargs.setdefault('editable', editable)
|
2019-02-26 16:33:06 +00:00
|
|
|
kwargs.setdefault('default', default)
|
2019-11-14 16:50:04 +00:00
|
|
|
super().__init__(*args, **kwargs)
|
2021-03-10 09:06:34 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
class UrlsafeTokenField(models.CharField):
|
|
|
|
|
"""
|
|
|
|
|
A field for storing a unique token in database.
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
def __init__(self, editable=False, max_length=128, factory=None, **kwargs):
|
|
|
|
|
"""
|
|
|
|
|
Parameters
|
|
|
|
|
----------
|
|
|
|
|
editable: bool
|
|
|
|
|
If true token is editable.
|
|
|
|
|
max_length: int
|
|
|
|
|
Maximum length of the token.
|
|
|
|
|
factory: callable
|
|
|
|
|
If provided, called with max_length of the field instance to generate token.
|
|
|
|
|
|
|
|
|
|
Raises
|
|
|
|
|
------
|
|
|
|
|
TypeError
|
|
|
|
|
non-callable value for factory is not supported.
|
|
|
|
|
"""
|
|
|
|
|
|
2023-03-20 17:37:49 +00:00
|
|
|
if factory is not None and not callable(factory):
|
2023-03-20 17:01:55 +00:00
|
|
|
raise TypeError("'factory' should either be a callable or 'None'")
|
2021-03-10 09:06:34 +00:00
|
|
|
self._factory = factory
|
|
|
|
|
|
|
|
|
|
kwargs.pop('default', None) # passing default value has not effect.
|
|
|
|
|
|
|
|
|
|
super().__init__(editable=editable, max_length=max_length, **kwargs)
|
|
|
|
|
|
|
|
|
|
def get_default(self):
|
|
|
|
|
if self._factory is not None:
|
|
|
|
|
return self._factory(self.max_length)
|
|
|
|
|
# generate a token of length x1.33 approx. trim up to max length
|
|
|
|
|
token = secrets.token_urlsafe(self.max_length)[:self.max_length]
|
|
|
|
|
return token
|
2021-04-02 08:28:51 +00:00
|
|
|
|
|
|
|
|
def deconstruct(self):
|
|
|
|
|
name, path, args, kwargs = super().deconstruct()
|
|
|
|
|
kwargs['factory'] = self._factory
|
|
|
|
|
return name, path, args, kwargs
|