Debian Codegraph @

model_utils/fields.py

raw
1 from __future__ import annotations
2
3 import secrets
4 import uuid
5 from collections.abc import Sequence
6 from typing import TYPE_CHECKING, Any, Union
7
8 from django.conf import settings
9 from django.core.exceptions import ValidationError
10 from django.db import models
11 from django.utils.timezone import now
12
13 if TYPE_CHECKING:
14 from collections.abc import Callable, Iterable
15 from datetime import date, datetime
16
17 DateTimeFieldBase = models.DateTimeField[Union[str, datetime, date], datetime]
18 else:
19 DateTimeFieldBase = models.DateTimeField
20
21 DEFAULT_CHOICES_NAME = 'STATUS'
22
23
24 class AutoCreatedField(DateTimeFieldBase):
25 """
26 A DateTimeField that automatically populates itself at
27 object creation.
28
29 By default, sets editable=False, default=datetime.now.
30
31 """
32
33 def __init__(self, *args: Any, **kwargs: Any):
34 kwargs.setdefault('editable', False)
35 kwargs.setdefault('default', now)
36 super().__init__(*args, **kwargs)
37
38
39 class AutoLastModifiedField(AutoCreatedField):
40 """
41 A DateTimeField that updates itself on each save() of the model.
42
43 By default, sets editable=False and default=datetime.now.
44
45 """
46 def get_default(self) -> datetime:
47 """Return the default value for this field."""
48 if not hasattr(self, "_default"):
49 self._default = super().get_default()
50 return self._default
51
52 def pre_save(self, model_instance: models.Model, add: bool) -> datetime:
53 value = now()
54 if add:
55 current_value = getattr(model_instance, self.attname, self.get_default())
56 if current_value != self.get_default():
57 # when creating an instance and the modified date is set
58 # don't change the value, assume the developer wants that
59 # control.
60 value = getattr(model_instance, self.attname)
61 else:
62 for field in model_instance._meta.get_fields():
63 if isinstance(field, AutoCreatedField):
64 value = getattr(model_instance, field.name)
65 break
66 setattr(model_instance, self.attname, value)
67 return value
68
69
70 class StatusField(models.CharField):
71 """
72 A CharField that looks for a ``STATUS`` class-attribute and
73 automatically uses that as ``choices``. The first option in
74 ``STATUS`` is set as the default.
75
76 Also has a default max_length so you don't have to worry about
77 setting that.
78
79 Also features a ``no_check_for_status`` argument to make sure
80 South can handle this field when it freezes a model.
81 """
82
83 def __init__(
84 self,
85 *args: Any,
86 no_check_for_status: bool = False,
87 choices_name: str = DEFAULT_CHOICES_NAME,
88 **kwargs: Any
89 ):
90 kwargs.setdefault('max_length', 100)
91 self.check_for_status = not no_check_for_status
92 self.choices_name = choices_name
93 super().__init__(*args, **kwargs)
94
95 def prepare_class(self, sender: type[models.Model], **kwargs: Any) -> None:
96 if not sender._meta.abstract and self.check_for_status:
97 assert hasattr(sender, self.choices_name), \
98 "To use StatusField, the model '%s' must have a %s choices class attribute." \
99 % (sender.__name__, self.choices_name)
100 self.choices = getattr(sender, self.choices_name)
101 if not self.has_default():
102 self.default = tuple(getattr(sender, self.choices_name))[0][0] # set first as default
103
104 def contribute_to_class(self, cls: type[models.Model], name: str, *args: Any, **kwargs: Any) -> None:
105 models.signals.class_prepared.connect(self.prepare_class, sender=cls)
106 # we don't set the real choices until class_prepared (so we can rely on
107 # the STATUS class attr being available), but we need to set some dummy
108 # choices now so the super method will add the get_FOO_display method
109 self.choices = [(0, 'dummy')]
110 super().contribute_to_class(cls, name, *args, **kwargs)
111
112 def deconstruct(self) -> tuple[str, str, Sequence[Any], dict[str, Any]]:
113 name, path, args, kwargs = super().deconstruct()
114 kwargs['no_check_for_status'] = True
115 return name, path, args, kwargs
116
117
118 class MonitorField(DateTimeFieldBase):
119 """
120 A DateTimeField that monitors another field on the same model and
121 sets itself to the current date/time whenever the monitored field
122 changes.
123
124 """
125
126 def __init__(self, *args: Any, monitor: str, when: Iterable[Any] | None = None, **kwargs: Any):
127 default = None if kwargs.get("null") else now
128 kwargs.setdefault('default', default)
129 self.monitor = monitor
130 self.when = None if when is None else set(when)
131 super().__init__(*args, **kwargs)
132
133 def contribute_to_class(self, cls: type[models.Model], name: str, *args: Any, **kwargs: Any) -> None:
134 self.monitor_attname = '_monitor_%s' % name
135 models.signals.post_init.connect(self._save_initial, sender=cls)
136 super().contribute_to_class(cls, name, *args, **kwargs)
137
138 def get_monitored_value(self, instance: models.Model) -> Any:
139 return getattr(instance, self.monitor)
140
141 def _save_initial(self, sender: type[models.Model], instance: models.Model, **kwargs: Any) -> None:
142 if self.monitor in instance.get_deferred_fields():
143 # Fix related to issue #241 to avoid recursive error on double monitor fields
144 return
145 setattr(instance, self.monitor_attname, self.get_monitored_value(instance))
146
147 def pre_save(self, model_instance: models.Model, add: bool) -> Any:
148 value = now()
149 previous = getattr(model_instance, self.monitor_attname, None)
150 current = self.get_monitored_value(model_instance)
151 if previous != current:
152 if self.when is None or current in self.when:
153 setattr(model_instance, self.attname, value)
154 self._save_initial(model_instance.__class__, model_instance)
155 return super().pre_save(model_instance, add)
156
157 def deconstruct(self) -> tuple[str, str, Sequence[Any], dict[str, Any]]:
158 name, path, args, kwargs = super().deconstruct()
159 kwargs['monitor'] = self.monitor
160 if self.when is not None:
161 kwargs['when'] = self.when
162 return name, path, args, kwargs
163
164
165 SPLIT_MARKER = getattr(settings, 'SPLIT_MARKER', '<!-- split -->')
166
167 # the number of paragraphs after which to split if no marker
168 SPLIT_DEFAULT_PARAGRAPHS = getattr(settings, 'SPLIT_DEFAULT_PARAGRAPHS', 2)
169
170
171 def _excerpt_field_name(name: str) -> str:
172 return '_%s_excerpt' % name
173
174
175 def get_excerpt(content: str) -> str:
176 excerpt: list[str] = []
177 default_excerpt = []
178 paras_seen = 0
179 for line in content.splitlines():
180 if not line.strip():
181 paras_seen += 1
182 if paras_seen < SPLIT_DEFAULT_PARAGRAPHS:
183 default_excerpt.append(line)
184 if line.strip() == SPLIT_MARKER:
185 return '\n'.join(excerpt)
186 excerpt.append(line)
187
188 return '\n'.join(default_excerpt)
189
190
191 class SplitText:
192 def __init__(self, instance: models.Model, field_name: str, excerpt_field_name: str):
193 # instead of storing actual values store a reference to the instance
194 # along with field names, this makes assignment possible
195 self.instance = instance
196 self.field_name = field_name
197 self.excerpt_field_name = excerpt_field_name
198
199 @property
200 def content(self) -> str:
201 return self.instance.__dict__[self.field_name]
202
203 @content.setter
204 def content(self, val: str) -> None:
205 setattr(self.instance, self.field_name, val)
206
207 @property
208 def excerpt(self) -> str:
209 return getattr(self.instance, self.excerpt_field_name)
210
211 @property
212 def has_more(self) -> bool:
213 return self.excerpt.strip() != self.content.strip()
214
215 def __str__(self) -> str:
216 return self.content
217
218
219 class SplitDescriptor:
220 def __init__(self, field: SplitField):
221 self.field = field
222 self.excerpt_field_name = _excerpt_field_name(self.field.name)
223
224 def __get__(self, instance: models.Model, owner: type[models.Model]) -> SplitText:
225 if instance is None:
226 raise AttributeError('Can only be accessed via an instance.')
227 return SplitText(instance, self.field.name, self.excerpt_field_name)
228
229 def __set__(self, obj: models.Model, value: SplitText | str) -> None:
230 if isinstance(value, SplitText):
231 obj.__dict__[self.field.name] = value.content
232 setattr(obj, self.excerpt_field_name, value.excerpt)
233 else:
234 obj.__dict__[self.field.name] = value
235
236
237 if TYPE_CHECKING:
238 _SplitFieldBase = models.TextField[Union[SplitText, str], SplitText]
239 else:
240 _SplitFieldBase = models.TextField
241
242
243 class SplitField(_SplitFieldBase):
244
245 def contribute_to_class(self, cls: type[models.Model], name: str, *args: Any, **kwargs: Any) -> None:
246 if not cls._meta.abstract:
247 excerpt_field: models.TextField = models.TextField(editable=False)
248 cls.add_to_class(_excerpt_field_name(name), excerpt_field)
249 super().contribute_to_class(cls, name, *args, **kwargs)
250 setattr(cls, self.name, SplitDescriptor(self))
251
252 def pre_save(self, model_instance: models.Model, add: bool) -> str:
253 value: SplitText = super().pre_save(model_instance, add)
254 excerpt = get_excerpt(value.content)
255 setattr(model_instance, _excerpt_field_name(self.attname), excerpt)
256 return value.content
257
258 def value_to_string(self, obj: models.Model) -> str:
259 value = self.value_from_object(obj)
260 return value.content
261
262 def get_prep_value(self, value: Any) -> str:
263 try:
264 return value.content
265 except AttributeError:
266 return value
267
268
269 class UUIDField(models.UUIDField):
270 """
271 A field for storing universally unique identifiers. Use Python UUID class.
272 """
273
274 def __init__(
275 self,
276 primary_key: bool = True,
277 version: int = 4,
278 editable: bool = False,
279 *args: Any,
280 **kwargs: Any
281 ):
282 """
283 Parameters
284 ----------
285 primary_key : bool
286 If True, this field is the primary key for the model.
287 version : int
288 An integer that set default UUID version.
289 editable : bool
290 If False, the field will not be displayed in the admin or any other ModelForm,
291 default is false.
292
293 Raises
294 ------
295 ValidationError
296 UUID version 2 is not supported.
297 """
298
299 if version == 2:
300 raise ValidationError(
301 'UUID version 2 is not supported.')
302
303 if version < 1 or version > 5:
304 raise ValidationError(
305 'UUID version is not valid.')
306
307 default: Callable[..., uuid.UUID]
308 if version == 1:
309 default = uuid.uuid1
310 elif version == 3:
311 default = uuid.uuid3
312 elif version == 4:
313 default = uuid.uuid4
314 elif version == 5:
315 default = uuid.uuid5
316
317 kwargs.setdefault('primary_key', primary_key)
318 kwargs.setdefault('editable', editable)
319 kwargs.setdefault('default', default)
320 super().__init__(*args, **kwargs)
321
322
323 class UrlsafeTokenField(models.CharField):
324 """
325 A field for storing a unique token in database.
326 """
327
328 max_length: int
329
330 def __init__(
331 self,
332 editable: bool = False,
333 max_length: int = 128,
334 factory: Callable[[int], str] | None = None,
335 **kwargs: Any
336 ):
337 """
338 Parameters
339 ----------
340 editable: bool
341 If true token is editable.
342 max_length: int
343 Maximum length of the token.
344 factory: callable
345 If provided, called with max_length of the field instance to generate token.
346
347 Raises
348 ------
349 TypeError
350 non-callable value for factory is not supported.
351 """
352
353 if factory is not None and not callable(factory):
354 raise TypeError("'factory' should either be a callable or 'None'")
355 self._factory = factory
356
357 kwargs.pop('default', None) # passing default value has not effect.
358
359 super().__init__(editable=editable, max_length=max_length, **kwargs)
360
361 def get_default(self) -> str:
362 if self._factory is not None:
363 return self._factory(self.max_length)
364 # generate a token of length x1.33 approx. trim up to max length
365 token = secrets.token_urlsafe(self.max_length)[:self.max_length]
366 return token
367
368 def deconstruct(self) -> tuple[str, str, Sequence[Any], dict[str, Any]]:
369 name, path, args, kwargs = super().deconstruct()
370 kwargs['factory'] = self._factory
371 return name, path, args, kwargs