models.py 24 KB

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