models.py 24 KB

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