Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# Imports
3# from datetime import timedelta
4# from django.core.exceptions import ImproperlyConfigured
5from django.db import models
6from django.utils.timezone import now
7from django.utils.translation import gettext_lazy as _
9# Exports
11__all__ = (
12 "AutoNowAddDateTimeField",
13 "AutoNowDateTimeField",
14)
16# Constants
18# Fields
21class AutoNowAddDateTimeField(models.DateTimeField):
22 """Automatically sets the date/time to "now" when the record is created.
24 It uses Django's timezone utils, which returns an aware or naive datetime, depending on ``settings.USE_TZ``.
25 However, use of ``USE_TZ`` is strongly recommended and is the default for new Django projects.
27 The ``editable`` field is also set to ``False`` by default.
29 """
31 description = _("Set the current date/time the first time the record is saved.")
33 def __init__(self, *args, **kwargs):
34 kwargs.setdefault('editable', False)
35 kwargs.setdefault('default', now)
36 super().__init__(*args, **kwargs)
39class AutoNowDateTimeField(AutoNowAddDateTimeField):
40 """Extends ``AutoNowAddField`` to also add the current date/time whenever the record is saved."""
42 description = _("Set the current date/time any time the record is saved.")
44 def pre_save(self, model_instance, add):
45 """Get the modified date/time automatically."""
46 if add:
47 value = self._get_new_value(model_instance)
48 else:
49 value = now()
51 setattr(model_instance, self.attname, value)
53 return value
55 def _get_new_value(self, model_instance):
56 """If an AutoAddedDateField is present, the added_dt and modified_dt will differ ever so slightly. Scan here to
57 handle such a situation.
59 :param model_instance: The current model instance.
61 :rtype: datetime
63 """
64 # If the value has already been given, assume it's been manually assigned.
65 value = getattr(model_instance, self.attname, self.get_default())
66 if value != self.get_default():
67 return value
68 else:
69 # noinspection PyProtectedMember
70 for field in model_instance._meta.get_fields():
71 if isinstance(field, AutoNowAddDateTimeField):
72 return getattr(model_instance, field.name)
74 return now()