Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

models.py 6.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. import json
  2. from django.conf import settings
  3. from django.contrib.admin.utils import quote
  4. from django.contrib.contenttypes.models import ContentType
  5. from django.db import models
  6. from django.urls import NoReverseMatch, reverse
  7. from django.utils import timezone
  8. from django.utils.text import get_text_list
  9. from django.utils.translation import gettext
  10. from django.utils.translation import gettext_lazy as _
  11. ADDITION = 1
  12. CHANGE = 2
  13. DELETION = 3
  14. ACTION_FLAG_CHOICES = (
  15. (ADDITION, _("Addition")),
  16. (CHANGE, _("Change")),
  17. (DELETION, _("Deletion")),
  18. )
  19. class LogEntryManager(models.Manager):
  20. use_in_migrations = True
  21. def log_action(
  22. self,
  23. user_id,
  24. content_type_id,
  25. object_id,
  26. object_repr,
  27. action_flag,
  28. change_message="",
  29. ):
  30. if isinstance(change_message, list):
  31. change_message = json.dumps(change_message)
  32. return self.model.objects.create(
  33. user_id=user_id,
  34. content_type_id=content_type_id,
  35. object_id=str(object_id),
  36. object_repr=object_repr[:200],
  37. action_flag=action_flag,
  38. change_message=change_message,
  39. )
  40. class LogEntry(models.Model):
  41. action_time = models.DateTimeField(
  42. _("action time"),
  43. default=timezone.now,
  44. editable=False,
  45. )
  46. user = models.ForeignKey(
  47. settings.AUTH_USER_MODEL,
  48. models.CASCADE,
  49. verbose_name=_("user"),
  50. )
  51. content_type = models.ForeignKey(
  52. ContentType,
  53. models.SET_NULL,
  54. verbose_name=_("content type"),
  55. blank=True,
  56. null=True,
  57. )
  58. object_id = models.TextField(_("object id"), blank=True, null=True)
  59. # Translators: 'repr' means representation
  60. # (https://docs.python.org/library/functions.html#repr)
  61. object_repr = models.CharField(_("object repr"), max_length=200)
  62. action_flag = models.PositiveSmallIntegerField(
  63. _("action flag"), choices=ACTION_FLAG_CHOICES
  64. )
  65. # change_message is either a string or a JSON structure
  66. change_message = models.TextField(_("change message"), blank=True)
  67. objects = LogEntryManager()
  68. class Meta:
  69. verbose_name = _("log entry")
  70. verbose_name_plural = _("log entries")
  71. db_table = "django_admin_log"
  72. ordering = ["-action_time"]
  73. def __repr__(self):
  74. return str(self.action_time)
  75. def __str__(self):
  76. if self.is_addition():
  77. return gettext("Added “%(object)s”.") % {"object": self.object_repr}
  78. elif self.is_change():
  79. return gettext("Changed “%(object)s” — %(changes)s") % {
  80. "object": self.object_repr,
  81. "changes": self.get_change_message(),
  82. }
  83. elif self.is_deletion():
  84. return gettext("Deleted “%(object)s.”") % {"object": self.object_repr}
  85. return gettext("LogEntry Object")
  86. def is_addition(self):
  87. return self.action_flag == ADDITION
  88. def is_change(self):
  89. return self.action_flag == CHANGE
  90. def is_deletion(self):
  91. return self.action_flag == DELETION
  92. def get_change_message(self):
  93. """
  94. If self.change_message is a JSON structure, interpret it as a change
  95. string, properly translated.
  96. """
  97. if self.change_message and self.change_message[0] == "[":
  98. try:
  99. change_message = json.loads(self.change_message)
  100. except json.JSONDecodeError:
  101. return self.change_message
  102. messages = []
  103. for sub_message in change_message:
  104. if "added" in sub_message:
  105. if sub_message["added"]:
  106. sub_message["added"]["name"] = gettext(
  107. sub_message["added"]["name"]
  108. )
  109. messages.append(
  110. gettext("Added {name} “{object}”.").format(
  111. **sub_message["added"]
  112. )
  113. )
  114. else:
  115. messages.append(gettext("Added."))
  116. elif "changed" in sub_message:
  117. sub_message["changed"]["fields"] = get_text_list(
  118. [
  119. gettext(field_name)
  120. for field_name in sub_message["changed"]["fields"]
  121. ],
  122. gettext("and"),
  123. )
  124. if "name" in sub_message["changed"]:
  125. sub_message["changed"]["name"] = gettext(
  126. sub_message["changed"]["name"]
  127. )
  128. messages.append(
  129. gettext("Changed {fields} for {name} “{object}”.").format(
  130. **sub_message["changed"]
  131. )
  132. )
  133. else:
  134. messages.append(
  135. gettext("Changed {fields}.").format(
  136. **sub_message["changed"]
  137. )
  138. )
  139. elif "deleted" in sub_message:
  140. sub_message["deleted"]["name"] = gettext(
  141. sub_message["deleted"]["name"]
  142. )
  143. messages.append(
  144. gettext("Deleted {name} “{object}”.").format(
  145. **sub_message["deleted"]
  146. )
  147. )
  148. change_message = " ".join(msg[0].upper() + msg[1:] for msg in messages)
  149. return change_message or gettext("No fields changed.")
  150. else:
  151. return self.change_message
  152. def get_edited_object(self):
  153. """Return the edited object represented by this log entry."""
  154. return self.content_type.get_object_for_this_type(pk=self.object_id)
  155. def get_admin_url(self):
  156. """
  157. Return the admin URL to edit the object represented by this log entry.
  158. """
  159. if self.content_type and self.object_id:
  160. url_name = "admin:%s_%s_change" % (
  161. self.content_type.app_label,
  162. self.content_type.model,
  163. )
  164. try:
  165. return reverse(url_name, args=(quote(self.object_id),))
  166. except NoReverseMatch:
  167. pass
  168. return None