models.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  1. import json
  2. import urllib.parse
  3. from django.conf import settings
  4. from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
  5. from django.core.validators import ValidationError
  6. from django.db import models
  7. from django.http import HttpResponse
  8. from django.urls import reverse
  9. from django.utils import timezone
  10. from django.utils.formats import date_format
  11. from django.utils.translation import gettext_lazy as _
  12. from rest_framework.utils.encoders import JSONEncoder
  13. from core.models import ContentType
  14. from extras.choices import *
  15. from extras.conditions import ConditionSet
  16. from extras.constants import *
  17. from extras.utils import image_upload
  18. from netbox.config import get_config
  19. from netbox.models import ChangeLoggedModel
  20. from netbox.models.features import (
  21. CloningMixin, CustomFieldsMixin, CustomLinksMixin, ExportTemplatesMixin, SyncedDataMixin, TagsMixin,
  22. )
  23. from utilities.querysets import RestrictedQuerySet
  24. from utilities.utils import clean_html, dict_to_querydict, render_jinja2
  25. __all__ = (
  26. 'Bookmark',
  27. 'CustomLink',
  28. 'EventRule',
  29. 'ExportTemplate',
  30. 'ImageAttachment',
  31. 'JournalEntry',
  32. 'SavedFilter',
  33. 'Webhook',
  34. )
  35. class EventRule(CustomFieldsMixin, ExportTemplatesMixin, TagsMixin, ChangeLoggedModel):
  36. """
  37. An EventRule defines an action to be taken automatically in response to a specific set of events, such as when a
  38. specific type of object is created, modified, or deleted. The action to be taken might entail transmitting a
  39. webhook or executing a custom script.
  40. """
  41. content_types = models.ManyToManyField(
  42. to='contenttypes.ContentType',
  43. related_name='eventrules',
  44. verbose_name=_('object types'),
  45. help_text=_("The object(s) to which this rule applies.")
  46. )
  47. name = models.CharField(
  48. verbose_name=_('name'),
  49. max_length=150,
  50. unique=True
  51. )
  52. description = models.CharField(
  53. verbose_name=_('description'),
  54. max_length=200,
  55. blank=True
  56. )
  57. type_create = models.BooleanField(
  58. verbose_name=_('on create'),
  59. default=False,
  60. help_text=_("Triggers when a matching object is created.")
  61. )
  62. type_update = models.BooleanField(
  63. verbose_name=_('on update'),
  64. default=False,
  65. help_text=_("Triggers when a matching object is updated.")
  66. )
  67. type_delete = models.BooleanField(
  68. verbose_name=_('on delete'),
  69. default=False,
  70. help_text=_("Triggers when a matching object is deleted.")
  71. )
  72. type_job_start = models.BooleanField(
  73. verbose_name=_('on job start'),
  74. default=False,
  75. help_text=_("Triggers when a job for a matching object is started.")
  76. )
  77. type_job_end = models.BooleanField(
  78. verbose_name=_('on job end'),
  79. default=False,
  80. help_text=_("Triggers when a job for a matching object terminates.")
  81. )
  82. enabled = models.BooleanField(
  83. verbose_name=_('enabled'),
  84. default=True
  85. )
  86. conditions = models.JSONField(
  87. verbose_name=_('conditions'),
  88. blank=True,
  89. null=True,
  90. help_text=_("A set of conditions which determine whether the event will be generated.")
  91. )
  92. # Action to take
  93. action_type = models.CharField(
  94. max_length=30,
  95. choices=EventRuleActionChoices,
  96. default=EventRuleActionChoices.WEBHOOK,
  97. verbose_name=_('action type')
  98. )
  99. action_object_type = models.ForeignKey(
  100. to='contenttypes.ContentType',
  101. related_name='eventrule_actions',
  102. on_delete=models.CASCADE
  103. )
  104. action_object_id = models.PositiveBigIntegerField(
  105. blank=True,
  106. null=True
  107. )
  108. action_object = GenericForeignKey(
  109. ct_field='action_object_type',
  110. fk_field='action_object_id'
  111. )
  112. action_parameters = models.JSONField(
  113. blank=True,
  114. null=True
  115. )
  116. action_data = models.JSONField(
  117. verbose_name=_('data'),
  118. blank=True,
  119. null=True,
  120. help_text=_("Additional data to pass to the action object")
  121. )
  122. comments = models.TextField(
  123. verbose_name=_('comments'),
  124. blank=True
  125. )
  126. class Meta:
  127. ordering = ('name',)
  128. indexes = (
  129. models.Index(fields=('action_object_type', 'action_object_id')),
  130. )
  131. verbose_name = _('event rule')
  132. verbose_name_plural = _('event rules')
  133. def __str__(self):
  134. return self.name
  135. def get_absolute_url(self):
  136. return reverse('extras:eventrule', args=[self.pk])
  137. def clean(self):
  138. super().clean()
  139. # At least one action type must be selected
  140. if not any([
  141. self.type_create, self.type_update, self.type_delete, self.type_job_start, self.type_job_end
  142. ]):
  143. raise ValidationError(
  144. _("At least one event type must be selected: create, update, delete, job start, and/or job end.")
  145. )
  146. # Validate that any conditions are in the correct format
  147. if self.conditions:
  148. try:
  149. ConditionSet(self.conditions)
  150. except ValueError as e:
  151. raise ValidationError({'conditions': e})
  152. def eval_conditions(self, data):
  153. """
  154. Test whether the given data meets the conditions of the event rule (if any). Return True
  155. if met or no conditions are specified.
  156. """
  157. if not self.conditions:
  158. return True
  159. return ConditionSet(self.conditions).eval(data)
  160. class Webhook(CustomFieldsMixin, ExportTemplatesMixin, TagsMixin, ChangeLoggedModel):
  161. """
  162. A Webhook defines a request that will be sent to a remote application when an object is created, updated, and/or
  163. delete in NetBox. The request will contain a representation of the object, which the remote application can act on.
  164. Each Webhook can be limited to firing only on certain actions or certain object types.
  165. """
  166. name = models.CharField(
  167. verbose_name=_('name'),
  168. max_length=150,
  169. unique=True
  170. )
  171. description = models.CharField(
  172. verbose_name=_('description'),
  173. max_length=200,
  174. blank=True
  175. )
  176. payload_url = models.CharField(
  177. max_length=500,
  178. verbose_name=_('URL'),
  179. help_text=_(
  180. "This URL will be called using the HTTP method defined when the webhook is called. Jinja2 template "
  181. "processing is supported with the same context as the request body."
  182. )
  183. )
  184. http_method = models.CharField(
  185. max_length=30,
  186. choices=WebhookHttpMethodChoices,
  187. default=WebhookHttpMethodChoices.METHOD_POST,
  188. verbose_name=_('HTTP method')
  189. )
  190. http_content_type = models.CharField(
  191. max_length=100,
  192. default=HTTP_CONTENT_TYPE_JSON,
  193. verbose_name=_('HTTP content type'),
  194. help_text=_(
  195. 'The complete list of official content types is available '
  196. '<a href="https://www.iana.org/assignments/media-types/media-types.xhtml">here</a>.'
  197. )
  198. )
  199. additional_headers = models.TextField(
  200. verbose_name=_('additional headers'),
  201. blank=True,
  202. help_text=_(
  203. "User-supplied HTTP headers to be sent with the request in addition to the HTTP content type. Headers "
  204. "should be defined in the format <code>Name: Value</code>. Jinja2 template processing is supported with "
  205. "the same context as the request body (below)."
  206. )
  207. )
  208. body_template = models.TextField(
  209. verbose_name=_('body template'),
  210. blank=True,
  211. help_text=_(
  212. "Jinja2 template for a custom request body. If blank, a JSON object representing the change will be "
  213. "included. Available context data includes: <code>event</code>, <code>model</code>, "
  214. "<code>timestamp</code>, <code>username</code>, <code>request_id</code>, and <code>data</code>."
  215. )
  216. )
  217. secret = models.CharField(
  218. verbose_name=_('secret'),
  219. max_length=255,
  220. blank=True,
  221. help_text=_(
  222. "When provided, the request will include a <code>X-Hook-Signature</code> header containing a HMAC hex "
  223. "digest of the payload body using the secret as the key. The secret is not transmitted in the request."
  224. )
  225. )
  226. ssl_verification = models.BooleanField(
  227. default=True,
  228. verbose_name=_('SSL verification'),
  229. help_text=_("Enable SSL certificate verification. Disable with caution!")
  230. )
  231. ca_file_path = models.CharField(
  232. max_length=4096,
  233. null=True,
  234. blank=True,
  235. verbose_name=_('CA File Path'),
  236. help_text=_(
  237. "The specific CA certificate file to use for SSL verification. Leave blank to use the system defaults."
  238. )
  239. )
  240. events = GenericRelation(
  241. EventRule,
  242. content_type_field='action_object_type',
  243. object_id_field='action_object_id'
  244. )
  245. class Meta:
  246. ordering = ('name',)
  247. verbose_name = _('webhook')
  248. verbose_name_plural = _('webhooks')
  249. def __str__(self):
  250. return self.name
  251. def get_absolute_url(self):
  252. return reverse('extras:webhook', args=[self.pk])
  253. @property
  254. def docs_url(self):
  255. return f'{settings.STATIC_URL}docs/models/extras/webhook/'
  256. def clean(self):
  257. super().clean()
  258. # CA file path requires SSL verification enabled
  259. if not self.ssl_verification and self.ca_file_path:
  260. raise ValidationError({
  261. 'ca_file_path': _('Do not specify a CA certificate file if SSL verification is disabled.')
  262. })
  263. def render_headers(self, context):
  264. """
  265. Render additional_headers and return a dict of Header: Value pairs.
  266. """
  267. if not self.additional_headers:
  268. return {}
  269. ret = {}
  270. data = render_jinja2(self.additional_headers, context)
  271. for line in data.splitlines():
  272. header, value = line.split(':', 1)
  273. ret[header.strip()] = value.strip()
  274. return ret
  275. def render_body(self, context):
  276. """
  277. Render the body template, if defined. Otherwise, jump the context as a JSON object.
  278. """
  279. if self.body_template:
  280. return render_jinja2(self.body_template, context)
  281. else:
  282. return json.dumps(context, cls=JSONEncoder)
  283. def render_payload_url(self, context):
  284. """
  285. Render the payload URL.
  286. """
  287. return render_jinja2(self.payload_url, context)
  288. class CustomLink(CloningMixin, ExportTemplatesMixin, ChangeLoggedModel):
  289. """
  290. A custom link to an external representation of a NetBox object. The link text and URL fields accept Jinja2 template
  291. code to be rendered with an object as context.
  292. """
  293. content_types = models.ManyToManyField(
  294. to='contenttypes.ContentType',
  295. related_name='custom_links',
  296. help_text=_('The object type(s) to which this link applies.')
  297. )
  298. name = models.CharField(
  299. verbose_name=_('name'),
  300. max_length=100,
  301. unique=True
  302. )
  303. enabled = models.BooleanField(
  304. verbose_name=_('enabled'),
  305. default=True
  306. )
  307. link_text = models.TextField(
  308. verbose_name=_('link text'),
  309. help_text=_("Jinja2 template code for link text")
  310. )
  311. link_url = models.TextField(
  312. verbose_name=_('link URL'),
  313. help_text=_("Jinja2 template code for link URL")
  314. )
  315. weight = models.PositiveSmallIntegerField(
  316. verbose_name=_('weight'),
  317. default=100
  318. )
  319. group_name = models.CharField(
  320. verbose_name=_('group name'),
  321. max_length=50,
  322. blank=True,
  323. help_text=_("Links with the same group will appear as a dropdown menu")
  324. )
  325. button_class = models.CharField(
  326. verbose_name=_('button class'),
  327. max_length=30,
  328. choices=CustomLinkButtonClassChoices,
  329. default=CustomLinkButtonClassChoices.DEFAULT,
  330. help_text=_("The class of the first link in a group will be used for the dropdown button")
  331. )
  332. new_window = models.BooleanField(
  333. verbose_name=_('new window'),
  334. default=False,
  335. help_text=_("Force link to open in a new window")
  336. )
  337. clone_fields = (
  338. 'content_types', 'enabled', 'weight', 'group_name', 'button_class', 'new_window',
  339. )
  340. class Meta:
  341. ordering = ['group_name', 'weight', 'name']
  342. verbose_name = _('custom link')
  343. verbose_name_plural = _('custom links')
  344. def __str__(self):
  345. return self.name
  346. def get_absolute_url(self):
  347. return reverse('extras:customlink', args=[self.pk])
  348. @property
  349. def docs_url(self):
  350. return f'{settings.STATIC_URL}docs/models/extras/customlink/'
  351. def render(self, context):
  352. """
  353. Render the CustomLink given the provided context, and return the text, link, and link_target.
  354. :param context: The context passed to Jinja2
  355. """
  356. text = render_jinja2(self.link_text, context).strip()
  357. if not text:
  358. return {}
  359. link = render_jinja2(self.link_url, context).strip()
  360. link_target = ' target="_blank"' if self.new_window else ''
  361. # Sanitize link text
  362. allowed_schemes = get_config().ALLOWED_URL_SCHEMES
  363. text = clean_html(text, allowed_schemes)
  364. # Sanitize link
  365. link = urllib.parse.quote(link, safe='/:?&=%+[]@#,;')
  366. # Verify link scheme is allowed
  367. result = urllib.parse.urlparse(link)
  368. if result.scheme and result.scheme not in allowed_schemes:
  369. link = ""
  370. return {
  371. 'text': text,
  372. 'link': link,
  373. 'link_target': link_target,
  374. }
  375. class ExportTemplate(SyncedDataMixin, CloningMixin, ExportTemplatesMixin, ChangeLoggedModel):
  376. content_types = models.ManyToManyField(
  377. to='contenttypes.ContentType',
  378. related_name='export_templates',
  379. help_text=_('The object type(s) to which this template applies.')
  380. )
  381. name = models.CharField(
  382. verbose_name=_('name'),
  383. max_length=100
  384. )
  385. description = models.CharField(
  386. verbose_name=_('description'),
  387. max_length=200,
  388. blank=True
  389. )
  390. template_code = models.TextField(
  391. help_text=_(
  392. "Jinja2 template code. The list of objects being exported is passed as a context variable named "
  393. "<code>queryset</code>."
  394. )
  395. )
  396. mime_type = models.CharField(
  397. max_length=50,
  398. blank=True,
  399. verbose_name=_('MIME type'),
  400. help_text=_('Defaults to <code>text/plain; charset=utf-8</code>')
  401. )
  402. file_extension = models.CharField(
  403. verbose_name=_('file extension'),
  404. max_length=15,
  405. blank=True,
  406. help_text=_('Extension to append to the rendered filename')
  407. )
  408. as_attachment = models.BooleanField(
  409. verbose_name=_('as attachment'),
  410. default=True,
  411. help_text=_("Download file as attachment")
  412. )
  413. clone_fields = (
  414. 'content_types', 'template_code', 'mime_type', 'file_extension', 'as_attachment',
  415. )
  416. class Meta:
  417. ordering = ('name',)
  418. verbose_name = _('export template')
  419. verbose_name_plural = _('export templates')
  420. def __str__(self):
  421. return self.name
  422. def get_absolute_url(self):
  423. return reverse('extras:exporttemplate', args=[self.pk])
  424. @property
  425. def docs_url(self):
  426. return f'{settings.STATIC_URL}docs/models/extras/exporttemplate/'
  427. def clean(self):
  428. super().clean()
  429. if self.name.lower() == 'table':
  430. raise ValidationError({
  431. 'name': _('"{name}" is a reserved name. Please choose a different name.').format(name=self.name)
  432. })
  433. def sync_data(self):
  434. """
  435. Synchronize template content from the designated DataFile (if any).
  436. """
  437. self.template_code = self.data_file.data_as_string
  438. sync_data.alters_data = True
  439. def render(self, queryset):
  440. """
  441. Render the contents of the template.
  442. """
  443. context = {
  444. 'queryset': queryset
  445. }
  446. output = render_jinja2(self.template_code, context)
  447. # Replace CRLF-style line terminators
  448. output = output.replace('\r\n', '\n')
  449. return output
  450. def render_to_response(self, queryset):
  451. """
  452. Render the template to an HTTP response, delivered as a named file attachment
  453. """
  454. output = self.render(queryset)
  455. mime_type = 'text/plain; charset=utf-8' if not self.mime_type else self.mime_type
  456. # Build the response
  457. response = HttpResponse(output, content_type=mime_type)
  458. if self.as_attachment:
  459. basename = queryset.model._meta.verbose_name_plural.replace(' ', '_')
  460. extension = f'.{self.file_extension}' if self.file_extension else ''
  461. filename = f'netbox_{basename}{extension}'
  462. response['Content-Disposition'] = f'attachment; filename="{filename}"'
  463. return response
  464. class SavedFilter(CloningMixin, ExportTemplatesMixin, ChangeLoggedModel):
  465. """
  466. A set of predefined keyword parameters that can be reused to filter for specific objects.
  467. """
  468. content_types = models.ManyToManyField(
  469. to='contenttypes.ContentType',
  470. related_name='saved_filters',
  471. help_text=_('The object type(s) to which this filter applies.')
  472. )
  473. name = models.CharField(
  474. verbose_name=_('name'),
  475. max_length=100,
  476. unique=True
  477. )
  478. slug = models.SlugField(
  479. verbose_name=_('slug'),
  480. max_length=100,
  481. unique=True
  482. )
  483. description = models.CharField(
  484. verbose_name=_('description'),
  485. max_length=200,
  486. blank=True
  487. )
  488. user = models.ForeignKey(
  489. to=settings.AUTH_USER_MODEL,
  490. on_delete=models.SET_NULL,
  491. blank=True,
  492. null=True
  493. )
  494. weight = models.PositiveSmallIntegerField(
  495. verbose_name=_('weight'),
  496. default=100
  497. )
  498. enabled = models.BooleanField(
  499. verbose_name=_('enabled'),
  500. default=True
  501. )
  502. shared = models.BooleanField(
  503. verbose_name=_('shared'),
  504. default=True
  505. )
  506. parameters = models.JSONField(
  507. verbose_name=_('parameters')
  508. )
  509. clone_fields = (
  510. 'content_types', 'weight', 'enabled', 'parameters',
  511. )
  512. class Meta:
  513. ordering = ('weight', 'name')
  514. verbose_name = _('saved filter')
  515. verbose_name_plural = _('saved filters')
  516. def __str__(self):
  517. return self.name
  518. def get_absolute_url(self):
  519. return reverse('extras:savedfilter', args=[self.pk])
  520. @property
  521. def docs_url(self):
  522. return f'{settings.STATIC_URL}docs/models/extras/savedfilter/'
  523. def clean(self):
  524. super().clean()
  525. # Verify that `parameters` is a JSON object
  526. if type(self.parameters) is not dict:
  527. raise ValidationError(
  528. {'parameters': _('Filter parameters must be stored as a dictionary of keyword arguments.')}
  529. )
  530. @property
  531. def url_params(self):
  532. qd = dict_to_querydict(self.parameters)
  533. return qd.urlencode()
  534. class ImageAttachment(ChangeLoggedModel):
  535. """
  536. An uploaded image which is associated with an object.
  537. """
  538. content_type = models.ForeignKey(
  539. to='contenttypes.ContentType',
  540. on_delete=models.CASCADE
  541. )
  542. object_id = models.PositiveBigIntegerField()
  543. parent = GenericForeignKey(
  544. ct_field='content_type',
  545. fk_field='object_id'
  546. )
  547. image = models.ImageField(
  548. upload_to=image_upload,
  549. height_field='image_height',
  550. width_field='image_width'
  551. )
  552. image_height = models.PositiveSmallIntegerField(
  553. verbose_name=_('image height'),
  554. )
  555. image_width = models.PositiveSmallIntegerField(
  556. verbose_name=_('image width'),
  557. )
  558. name = models.CharField(
  559. verbose_name=_('name'),
  560. max_length=50,
  561. blank=True
  562. )
  563. objects = RestrictedQuerySet.as_manager()
  564. clone_fields = ('content_type', 'object_id')
  565. class Meta:
  566. ordering = ('name', 'pk') # name may be non-unique
  567. indexes = (
  568. models.Index(fields=('content_type', 'object_id')),
  569. )
  570. verbose_name = _('image attachment')
  571. verbose_name_plural = _('image attachments')
  572. def __str__(self):
  573. if self.name:
  574. return self.name
  575. filename = self.image.name.rsplit('/', 1)[-1]
  576. return filename.split('_', 2)[2]
  577. def clean(self):
  578. super().clean()
  579. # Validate the assigned object type
  580. if self.content_type not in ContentType.objects.with_feature('image_attachments'):
  581. raise ValidationError(
  582. _("Image attachments cannot be assigned to this object type ({type}).").format(type=self.content_type)
  583. )
  584. def delete(self, *args, **kwargs):
  585. _name = self.image.name
  586. super().delete(*args, **kwargs)
  587. # Delete file from disk
  588. self.image.delete(save=False)
  589. # Deleting the file erases its name. We restore the image's filename here in case we still need to reference it
  590. # before the request finishes. (For example, to display a message indicating the ImageAttachment was deleted.)
  591. self.image.name = _name
  592. @property
  593. def size(self):
  594. """
  595. Wrapper around `image.size` to suppress an OSError in case the file is inaccessible. Also opportunistically
  596. catch other exceptions that we know other storage back-ends to throw.
  597. """
  598. expected_exceptions = [OSError]
  599. try:
  600. from botocore.exceptions import ClientError
  601. expected_exceptions.append(ClientError)
  602. except ImportError:
  603. pass
  604. try:
  605. return self.image.size
  606. except tuple(expected_exceptions):
  607. return None
  608. def to_objectchange(self, action):
  609. objectchange = super().to_objectchange(action)
  610. objectchange.related_object = self.parent
  611. return objectchange
  612. class JournalEntry(CustomFieldsMixin, CustomLinksMixin, TagsMixin, ExportTemplatesMixin, ChangeLoggedModel):
  613. """
  614. A historical remark concerning an object; collectively, these form an object's journal. The journal is used to
  615. preserve historical context around an object, and complements NetBox's built-in change logging. For example, you
  616. might record a new journal entry when a device undergoes maintenance, or when a prefix is expanded.
  617. """
  618. assigned_object_type = models.ForeignKey(
  619. to='contenttypes.ContentType',
  620. on_delete=models.CASCADE
  621. )
  622. assigned_object_id = models.PositiveBigIntegerField()
  623. assigned_object = GenericForeignKey(
  624. ct_field='assigned_object_type',
  625. fk_field='assigned_object_id'
  626. )
  627. created_by = models.ForeignKey(
  628. to=settings.AUTH_USER_MODEL,
  629. on_delete=models.SET_NULL,
  630. blank=True,
  631. null=True
  632. )
  633. kind = models.CharField(
  634. verbose_name=_('kind'),
  635. max_length=30,
  636. choices=JournalEntryKindChoices,
  637. default=JournalEntryKindChoices.KIND_INFO
  638. )
  639. comments = models.TextField(
  640. verbose_name=_('comments'),
  641. )
  642. class Meta:
  643. ordering = ('-created',)
  644. indexes = (
  645. models.Index(fields=('assigned_object_type', 'assigned_object_id')),
  646. )
  647. verbose_name = _('journal entry')
  648. verbose_name_plural = _('journal entries')
  649. def __str__(self):
  650. created = timezone.localtime(self.created)
  651. return f"{date_format(created, format='SHORT_DATETIME_FORMAT')} ({self.get_kind_display()})"
  652. def get_absolute_url(self):
  653. return reverse('extras:journalentry', args=[self.pk])
  654. def clean(self):
  655. super().clean()
  656. # Validate the assigned object type
  657. if self.assigned_object_type not in ContentType.objects.with_feature('journaling'):
  658. raise ValidationError(
  659. _("Journaling is not supported for this object type ({type}).").format(type=self.assigned_object_type)
  660. )
  661. def get_kind_color(self):
  662. return JournalEntryKindChoices.colors.get(self.kind)
  663. class Bookmark(models.Model):
  664. """
  665. An object bookmarked by a User.
  666. """
  667. created = models.DateTimeField(
  668. verbose_name=_('created'),
  669. auto_now_add=True
  670. )
  671. object_type = models.ForeignKey(
  672. to='contenttypes.ContentType',
  673. on_delete=models.PROTECT
  674. )
  675. object_id = models.PositiveBigIntegerField()
  676. object = GenericForeignKey(
  677. ct_field='object_type',
  678. fk_field='object_id'
  679. )
  680. user = models.ForeignKey(
  681. to=settings.AUTH_USER_MODEL,
  682. on_delete=models.PROTECT
  683. )
  684. objects = RestrictedQuerySet.as_manager()
  685. class Meta:
  686. ordering = ('created', 'pk')
  687. indexes = (
  688. models.Index(fields=('object_type', 'object_id')),
  689. )
  690. constraints = (
  691. models.UniqueConstraint(
  692. fields=('object_type', 'object_id', 'user'),
  693. name='%(app_label)s_%(class)s_unique_per_object_and_user'
  694. ),
  695. )
  696. verbose_name = _('bookmark')
  697. verbose_name_plural = _('bookmarks')
  698. def __str__(self):
  699. if self.object:
  700. return str(self.object)
  701. return super().__str__()
  702. def clean(self):
  703. super().clean()
  704. # Validate the assigned object type
  705. if self.object_type not in ContentType.objects.with_feature('bookmarks'):
  706. raise ValidationError(
  707. _("Bookmarks cannot be assigned to this object type ({type}).").format(type=self.object_type)
  708. )