Hide keyboard shortcuts

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 

2 

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 _ 

8 

9# Exports 

10 

11__all__ = ( 

12 "AutoNowAddDateTimeField", 

13 "AutoNowDateTimeField", 

14) 

15 

16# Constants 

17 

18# Fields 

19 

20 

21class AutoNowAddDateTimeField(models.DateTimeField): 

22 """Automatically sets the date/time to "now" when the record is created. 

23 

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. 

26 

27 The ``editable`` field is also set to ``False`` by default. 

28 

29 """ 

30 

31 description = _("Set the current date/time the first time the record is saved.") 

32 

33 def __init__(self, *args, **kwargs): 

34 kwargs.setdefault('editable', False) 

35 kwargs.setdefault('default', now) 

36 super().__init__(*args, **kwargs) 

37 

38 

39class AutoNowDateTimeField(AutoNowAddDateTimeField): 

40 """Extends ``AutoNowAddField`` to also add the current date/time whenever the record is saved.""" 

41 

42 description = _("Set the current date/time any time the record is saved.") 

43 

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() 

50 

51 setattr(model_instance, self.attname, value) 

52 

53 return value 

54 

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. 

58 

59 :param model_instance: The current model instance. 

60 

61 :rtype: datetime 

62 

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) 

73 

74 return now()