2
0

models.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  1. from collections import OrderedDict
  2. from datetime import date
  3. from django.contrib.auth.models import User
  4. from django.contrib.contenttypes.fields import GenericForeignKey
  5. from django.contrib.contenttypes.models import ContentType
  6. from django.contrib.postgres.fields import JSONField
  7. from django.core.validators import ValidationError
  8. from django.db import models
  9. from django.http import HttpResponse
  10. from django.template import Template, Context
  11. from django.urls import reverse
  12. from jinja2 import Environment
  13. from taggit.models import TagBase, GenericTaggedItemBase
  14. from utilities.fields import ColorField
  15. from utilities.utils import deepmerge, model_names_to_filter_dict
  16. from .constants import *
  17. from .querysets import ConfigContextQuerySet
  18. #
  19. # Webhooks
  20. #
  21. def get_webhook_models():
  22. return model_names_to_filter_dict(WEBHOOK_MODELS)
  23. class Webhook(models.Model):
  24. """
  25. A Webhook defines a request that will be sent to a remote application when an object is created, updated, and/or
  26. delete in NetBox. The request will contain a representation of the object, which the remote application can act on.
  27. Each Webhook can be limited to firing only on certain actions or certain object types.
  28. """
  29. obj_type = models.ManyToManyField(
  30. to=ContentType,
  31. related_name='webhooks',
  32. verbose_name='Object types',
  33. limit_choices_to=get_webhook_models,
  34. help_text="The object(s) to which this Webhook applies."
  35. )
  36. name = models.CharField(
  37. max_length=150,
  38. unique=True
  39. )
  40. type_create = models.BooleanField(
  41. default=False,
  42. help_text="Call this webhook when a matching object is created."
  43. )
  44. type_update = models.BooleanField(
  45. default=False,
  46. help_text="Call this webhook when a matching object is updated."
  47. )
  48. type_delete = models.BooleanField(
  49. default=False,
  50. help_text="Call this webhook when a matching object is deleted."
  51. )
  52. payload_url = models.CharField(
  53. max_length=500,
  54. verbose_name='URL',
  55. help_text="A POST will be sent to this URL when the webhook is called."
  56. )
  57. http_content_type = models.PositiveSmallIntegerField(
  58. choices=WEBHOOK_CT_CHOICES,
  59. default=WEBHOOK_CT_JSON,
  60. verbose_name='HTTP content type'
  61. )
  62. secret = models.CharField(
  63. max_length=255,
  64. blank=True,
  65. help_text="When provided, the request will include a 'X-Hook-Signature' "
  66. "header containing a HMAC hex digest of the payload body using "
  67. "the secret as the key. The secret is not transmitted in "
  68. "the request."
  69. )
  70. enabled = models.BooleanField(
  71. default=True
  72. )
  73. ssl_verification = models.BooleanField(
  74. default=True,
  75. verbose_name='SSL verification',
  76. help_text="Enable SSL certificate verification. Disable with caution!"
  77. )
  78. ca_file_path = models.CharField(
  79. max_length=4096,
  80. null=True,
  81. blank=True,
  82. verbose_name='CA File Path',
  83. help_text='The specific CA certificate file to use for SSL verification. '
  84. 'Leave blank to use the system defaults.'
  85. )
  86. class Meta:
  87. unique_together = ('payload_url', 'type_create', 'type_update', 'type_delete',)
  88. def __str__(self):
  89. return self.name
  90. def clean(self):
  91. """
  92. Validate model
  93. """
  94. if not self.type_create and not self.type_delete and not self.type_update:
  95. raise ValidationError(
  96. "You must select at least one type: create, update, and/or delete."
  97. )
  98. if not self.ssl_verification and self.ca_file_path:
  99. raise ValidationError({
  100. 'ca_file_path': 'Do not specify a CA certificate file if SSL verification is dissabled.'
  101. })
  102. #
  103. # Custom fields
  104. #
  105. class CustomFieldModel(models.Model):
  106. _cf = None
  107. class Meta:
  108. abstract = True
  109. @property
  110. def cf(self):
  111. """
  112. Name-based CustomFieldValue accessor for use in templates
  113. """
  114. if self._cf is None:
  115. # Cache all custom field values for this instance
  116. self._cf = {
  117. field.name: value for field, value in self.get_custom_fields().items()
  118. }
  119. return self._cf
  120. def get_custom_fields(self):
  121. """
  122. Return a dictionary of custom fields for a single object in the form {<field>: value}.
  123. """
  124. # Find all custom fields applicable to this type of object
  125. content_type = ContentType.objects.get_for_model(self)
  126. fields = CustomField.objects.filter(obj_type=content_type)
  127. # If the object exists, populate its custom fields with values
  128. if hasattr(self, 'pk'):
  129. values = self.custom_field_values.all()
  130. values_dict = {cfv.field_id: cfv.value for cfv in values}
  131. return OrderedDict([(field, values_dict.get(field.pk)) for field in fields])
  132. else:
  133. return OrderedDict([(field, None) for field in fields])
  134. def get_custom_field_models():
  135. return model_names_to_filter_dict(CUSTOMFIELD_MODELS)
  136. class CustomField(models.Model):
  137. obj_type = models.ManyToManyField(
  138. to=ContentType,
  139. related_name='custom_fields',
  140. verbose_name='Object(s)',
  141. limit_choices_to=get_custom_field_models,
  142. help_text='The object(s) to which this field applies.'
  143. )
  144. type = models.PositiveSmallIntegerField(
  145. choices=CUSTOMFIELD_TYPE_CHOICES,
  146. default=CF_TYPE_TEXT
  147. )
  148. name = models.CharField(
  149. max_length=50,
  150. unique=True
  151. )
  152. label = models.CharField(
  153. max_length=50,
  154. blank=True,
  155. help_text='Name of the field as displayed to users (if not provided, '
  156. 'the field\'s name will be used)'
  157. )
  158. description = models.CharField(
  159. max_length=100,
  160. blank=True
  161. )
  162. required = models.BooleanField(
  163. default=False,
  164. help_text='If true, this field is required when creating new objects '
  165. 'or editing an existing object.'
  166. )
  167. filter_logic = models.PositiveSmallIntegerField(
  168. choices=CF_FILTER_CHOICES,
  169. default=CF_FILTER_LOOSE,
  170. help_text='Loose matches any instance of a given string; exact '
  171. 'matches the entire field.'
  172. )
  173. default = models.CharField(
  174. max_length=100,
  175. blank=True,
  176. help_text='Default value for the field. Use "true" or "false" for booleans.'
  177. )
  178. weight = models.PositiveSmallIntegerField(
  179. default=100,
  180. help_text='Fields with higher weights appear lower in a form.'
  181. )
  182. class Meta:
  183. ordering = ['weight', 'name']
  184. def __str__(self):
  185. return self.label or self.name.replace('_', ' ').capitalize()
  186. def serialize_value(self, value):
  187. """
  188. Serialize the given value to a string suitable for storage as a CustomFieldValue
  189. """
  190. if value is None:
  191. return ''
  192. if self.type == CF_TYPE_BOOLEAN:
  193. return str(int(bool(value)))
  194. if self.type == CF_TYPE_DATE:
  195. # Could be date/datetime object or string
  196. try:
  197. return value.strftime('%Y-%m-%d')
  198. except AttributeError:
  199. return value
  200. if self.type == CF_TYPE_SELECT:
  201. # Could be ModelChoiceField or TypedChoiceField
  202. return str(value.id) if hasattr(value, 'id') else str(value)
  203. return value
  204. def deserialize_value(self, serialized_value):
  205. """
  206. Convert a string into the object it represents depending on the type of field
  207. """
  208. if serialized_value == '':
  209. return None
  210. if self.type == CF_TYPE_INTEGER:
  211. return int(serialized_value)
  212. if self.type == CF_TYPE_BOOLEAN:
  213. return bool(int(serialized_value))
  214. if self.type == CF_TYPE_DATE:
  215. # Read date as YYYY-MM-DD
  216. return date(*[int(n) for n in serialized_value.split('-')])
  217. if self.type == CF_TYPE_SELECT:
  218. return self.choices.get(pk=int(serialized_value))
  219. return serialized_value
  220. class CustomFieldValue(models.Model):
  221. field = models.ForeignKey(
  222. to='extras.CustomField',
  223. on_delete=models.CASCADE,
  224. related_name='values'
  225. )
  226. obj_type = models.ForeignKey(
  227. to=ContentType,
  228. on_delete=models.PROTECT,
  229. related_name='+'
  230. )
  231. obj_id = models.PositiveIntegerField()
  232. obj = GenericForeignKey(
  233. ct_field='obj_type',
  234. fk_field='obj_id'
  235. )
  236. serialized_value = models.CharField(
  237. max_length=255
  238. )
  239. class Meta:
  240. ordering = ['obj_type', 'obj_id']
  241. unique_together = ['field', 'obj_type', 'obj_id']
  242. def __str__(self):
  243. return '{} {}'.format(self.obj, self.field)
  244. @property
  245. def value(self):
  246. return self.field.deserialize_value(self.serialized_value)
  247. @value.setter
  248. def value(self, value):
  249. self.serialized_value = self.field.serialize_value(value)
  250. def save(self, *args, **kwargs):
  251. # Delete this object if it no longer has a value to store
  252. if self.pk and self.value is None:
  253. self.delete()
  254. else:
  255. super().save(*args, **kwargs)
  256. class CustomFieldChoice(models.Model):
  257. field = models.ForeignKey(
  258. to='extras.CustomField',
  259. on_delete=models.CASCADE,
  260. related_name='choices',
  261. limit_choices_to={'type': CF_TYPE_SELECT}
  262. )
  263. value = models.CharField(
  264. max_length=100
  265. )
  266. weight = models.PositiveSmallIntegerField(
  267. default=100,
  268. help_text='Higher weights appear lower in the list'
  269. )
  270. class Meta:
  271. ordering = ['field', 'weight', 'value']
  272. unique_together = ['field', 'value']
  273. def __str__(self):
  274. return self.value
  275. def clean(self):
  276. if self.field.type != CF_TYPE_SELECT:
  277. raise ValidationError("Custom field choices can only be assigned to selection fields.")
  278. def delete(self, using=None, keep_parents=False):
  279. # When deleting a CustomFieldChoice, delete all CustomFieldValues which point to it
  280. pk = self.pk
  281. super().delete(using, keep_parents)
  282. CustomFieldValue.objects.filter(field__type=CF_TYPE_SELECT, serialized_value=str(pk)).delete()
  283. #
  284. # Custom links
  285. #
  286. def get_custom_link_models():
  287. return model_names_to_filter_dict(CUSTOMLINK_MODELS)
  288. class CustomLink(models.Model):
  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_type = models.ForeignKey(
  294. to=ContentType,
  295. on_delete=models.CASCADE,
  296. limit_choices_to=get_custom_link_models
  297. )
  298. name = models.CharField(
  299. max_length=100,
  300. unique=True
  301. )
  302. text = models.CharField(
  303. max_length=500,
  304. help_text="Jinja2 template code for link text"
  305. )
  306. url = models.CharField(
  307. max_length=500,
  308. verbose_name='URL',
  309. help_text="Jinja2 template code for link URL"
  310. )
  311. weight = models.PositiveSmallIntegerField(
  312. default=100
  313. )
  314. group_name = models.CharField(
  315. max_length=50,
  316. blank=True,
  317. help_text="Links with the same group will appear as a dropdown menu"
  318. )
  319. button_class = models.CharField(
  320. max_length=30,
  321. choices=BUTTON_CLASS_CHOICES,
  322. default=BUTTON_CLASS_DEFAULT,
  323. help_text="The class of the first link in a group will be used for the dropdown button"
  324. )
  325. new_window = models.BooleanField(
  326. help_text="Force link to open in a new window"
  327. )
  328. class Meta:
  329. ordering = ['group_name', 'weight', 'name']
  330. def __str__(self):
  331. return self.name
  332. #
  333. # Graphs
  334. #
  335. class Graph(models.Model):
  336. type = models.PositiveSmallIntegerField(
  337. choices=GRAPH_TYPE_CHOICES
  338. )
  339. weight = models.PositiveSmallIntegerField(
  340. default=1000
  341. )
  342. name = models.CharField(
  343. max_length=100,
  344. verbose_name='Name'
  345. )
  346. source = models.CharField(
  347. max_length=500,
  348. verbose_name='Source URL'
  349. )
  350. link = models.URLField(
  351. blank=True,
  352. verbose_name='Link URL'
  353. )
  354. class Meta:
  355. ordering = ['type', 'weight', 'name']
  356. def __str__(self):
  357. return self.name
  358. def embed_url(self, obj):
  359. template = Template(self.source)
  360. return template.render(Context({'obj': obj}))
  361. def embed_link(self, obj):
  362. if self.link is None:
  363. return ''
  364. template = Template(self.link)
  365. return template.render(Context({'obj': obj}))
  366. #
  367. # Export templates
  368. #
  369. def get_export_template_models():
  370. return model_names_to_filter_dict(EXPORTTEMPLATE_MODELS)
  371. class ExportTemplate(models.Model):
  372. content_type = models.ForeignKey(
  373. to=ContentType,
  374. on_delete=models.CASCADE,
  375. limit_choices_to=get_export_template_models
  376. )
  377. name = models.CharField(
  378. max_length=100
  379. )
  380. description = models.CharField(
  381. max_length=200,
  382. blank=True
  383. )
  384. template_language = models.PositiveSmallIntegerField(
  385. choices=TEMPLATE_LANGUAGE_CHOICES,
  386. default=TEMPLATE_LANGUAGE_JINJA2
  387. )
  388. template_code = models.TextField(
  389. help_text='The list of objects being exported is passed as a context variable named <code>queryset</code>.'
  390. )
  391. mime_type = models.CharField(
  392. max_length=50,
  393. blank=True,
  394. verbose_name='MIME type',
  395. help_text='Defaults to <code>text/plain</code>'
  396. )
  397. file_extension = models.CharField(
  398. max_length=15,
  399. blank=True,
  400. help_text='Extension to append to the rendered filename'
  401. )
  402. class Meta:
  403. ordering = ['content_type', 'name']
  404. unique_together = [
  405. ['content_type', 'name']
  406. ]
  407. def __str__(self):
  408. return '{}: {}'.format(self.content_type, self.name)
  409. def render(self, queryset):
  410. """
  411. Render the contents of the template.
  412. """
  413. context = {
  414. 'queryset': queryset
  415. }
  416. if self.template_language == TEMPLATE_LANGUAGE_DJANGO:
  417. template = Template(self.template_code)
  418. output = template.render(Context(context))
  419. elif self.template_language == TEMPLATE_LANGUAGE_JINJA2:
  420. template = Environment().from_string(source=self.template_code)
  421. output = template.render(**context)
  422. else:
  423. return None
  424. # Replace CRLF-style line terminators
  425. output = output.replace('\r\n', '\n')
  426. return output
  427. def render_to_response(self, queryset):
  428. """
  429. Render the template to an HTTP response, delivered as a named file attachment
  430. """
  431. output = self.render(queryset)
  432. mime_type = 'text/plain' if not self.mime_type else self.mime_type
  433. # Build the response
  434. response = HttpResponse(output, content_type=mime_type)
  435. filename = 'netbox_{}{}'.format(
  436. queryset.model._meta.verbose_name_plural,
  437. '.{}'.format(self.file_extension) if self.file_extension else ''
  438. )
  439. response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
  440. return response
  441. #
  442. # Image attachments
  443. #
  444. def image_upload(instance, filename):
  445. path = 'image-attachments/'
  446. # Rename the file to the provided name, if any. Attempt to preserve the file extension.
  447. extension = filename.rsplit('.')[-1].lower()
  448. if instance.name and extension in ['bmp', 'gif', 'jpeg', 'jpg', 'png']:
  449. filename = '.'.join([instance.name, extension])
  450. elif instance.name:
  451. filename = instance.name
  452. return '{}{}_{}_{}'.format(path, instance.content_type.name, instance.object_id, filename)
  453. class ImageAttachment(models.Model):
  454. """
  455. An uploaded image which is associated with an object.
  456. """
  457. content_type = models.ForeignKey(
  458. to=ContentType,
  459. on_delete=models.CASCADE
  460. )
  461. object_id = models.PositiveIntegerField()
  462. parent = GenericForeignKey(
  463. ct_field='content_type',
  464. fk_field='object_id'
  465. )
  466. image = models.ImageField(
  467. upload_to=image_upload,
  468. height_field='image_height',
  469. width_field='image_width'
  470. )
  471. image_height = models.PositiveSmallIntegerField()
  472. image_width = models.PositiveSmallIntegerField()
  473. name = models.CharField(
  474. max_length=50,
  475. blank=True
  476. )
  477. created = models.DateTimeField(
  478. auto_now_add=True
  479. )
  480. class Meta:
  481. ordering = ['name']
  482. def __str__(self):
  483. if self.name:
  484. return self.name
  485. filename = self.image.name.rsplit('/', 1)[-1]
  486. return filename.split('_', 2)[2]
  487. def delete(self, *args, **kwargs):
  488. _name = self.image.name
  489. super().delete(*args, **kwargs)
  490. # Delete file from disk
  491. self.image.delete(save=False)
  492. # Deleting the file erases its name. We restore the image's filename here in case we still need to reference it
  493. # before the request finishes. (For example, to display a message indicating the ImageAttachment was deleted.)
  494. self.image.name = _name
  495. @property
  496. def size(self):
  497. """
  498. Wrapper around `image.size` to suppress an OSError in case the file is inaccessible.
  499. """
  500. try:
  501. return self.image.size
  502. except OSError:
  503. return None
  504. #
  505. # Config contexts
  506. #
  507. class ConfigContext(models.Model):
  508. """
  509. A ConfigContext represents a set of arbitrary data available to any Device or VirtualMachine matching its assigned
  510. qualifiers (region, site, etc.). For example, the data stored in a ConfigContext assigned to site A and tenant B
  511. will be available to a Device in site A assigned to tenant B. Data is stored in JSON format.
  512. """
  513. name = models.CharField(
  514. max_length=100,
  515. unique=True
  516. )
  517. weight = models.PositiveSmallIntegerField(
  518. default=1000
  519. )
  520. description = models.CharField(
  521. max_length=100,
  522. blank=True
  523. )
  524. is_active = models.BooleanField(
  525. default=True,
  526. )
  527. regions = models.ManyToManyField(
  528. to='dcim.Region',
  529. related_name='+',
  530. blank=True
  531. )
  532. sites = models.ManyToManyField(
  533. to='dcim.Site',
  534. related_name='+',
  535. blank=True
  536. )
  537. roles = models.ManyToManyField(
  538. to='dcim.DeviceRole',
  539. related_name='+',
  540. blank=True
  541. )
  542. platforms = models.ManyToManyField(
  543. to='dcim.Platform',
  544. related_name='+',
  545. blank=True
  546. )
  547. tenant_groups = models.ManyToManyField(
  548. to='tenancy.TenantGroup',
  549. related_name='+',
  550. blank=True
  551. )
  552. tenants = models.ManyToManyField(
  553. to='tenancy.Tenant',
  554. related_name='+',
  555. blank=True
  556. )
  557. data = JSONField()
  558. objects = ConfigContextQuerySet.as_manager()
  559. class Meta:
  560. ordering = ['weight', 'name']
  561. def __str__(self):
  562. return self.name
  563. def get_absolute_url(self):
  564. return reverse('extras:configcontext', kwargs={'pk': self.pk})
  565. def clean(self):
  566. # Verify that JSON data is provided as an object
  567. if type(self.data) is not dict:
  568. raise ValidationError(
  569. {'data': 'JSON data must be in object form. Example: {"foo": 123}'}
  570. )
  571. class ConfigContextModel(models.Model):
  572. """
  573. A model which includes local configuration context data. This local data will override any inherited data from
  574. ConfigContexts.
  575. """
  576. local_context_data = JSONField(
  577. blank=True,
  578. null=True,
  579. )
  580. class Meta:
  581. abstract = True
  582. def get_config_context(self):
  583. """
  584. Return the rendered configuration context for a device or VM.
  585. """
  586. # Compile all config data, overwriting lower-weight values with higher-weight values where a collision occurs
  587. data = OrderedDict()
  588. for context in ConfigContext.objects.get_for_object(self):
  589. data = deepmerge(data, context.data)
  590. # If the object has local config context data defined, merge it last
  591. if self.local_context_data:
  592. data = deepmerge(data, self.local_context_data)
  593. return data
  594. def clean(self):
  595. super().clean()
  596. # Verify that JSON data is provided as an object
  597. if self.local_context_data and type(self.local_context_data) is not dict:
  598. raise ValidationError(
  599. {'local_context_data': 'JSON data must be in object form. Example: {"foo": 123}'}
  600. )
  601. #
  602. # Custom scripts
  603. #
  604. class Script(models.Model):
  605. """
  606. Dummy model used to generate permissions for custom scripts. Does not exist in the database.
  607. """
  608. class Meta:
  609. managed = False
  610. permissions = (
  611. ('run_script', 'Can run script'),
  612. )
  613. #
  614. # Report results
  615. #
  616. class ReportResult(models.Model):
  617. """
  618. This model stores the results from running a user-defined report.
  619. """
  620. report = models.CharField(
  621. max_length=255,
  622. unique=True
  623. )
  624. created = models.DateTimeField(
  625. auto_now_add=True
  626. )
  627. user = models.ForeignKey(
  628. to=User,
  629. on_delete=models.SET_NULL,
  630. related_name='+',
  631. blank=True,
  632. null=True
  633. )
  634. failed = models.BooleanField()
  635. data = JSONField()
  636. class Meta:
  637. ordering = ['report']
  638. #
  639. # Change logging
  640. #
  641. class ObjectChange(models.Model):
  642. """
  643. Record a change to an object and the user account associated with that change. A change record may optionally
  644. indicate an object related to the one being changed. For example, a change to an interface may also indicate the
  645. parent device. This will ensure changes made to component models appear in the parent model's changelog.
  646. """
  647. time = models.DateTimeField(
  648. auto_now_add=True,
  649. editable=False,
  650. db_index=True
  651. )
  652. user = models.ForeignKey(
  653. to=User,
  654. on_delete=models.SET_NULL,
  655. related_name='changes',
  656. blank=True,
  657. null=True
  658. )
  659. user_name = models.CharField(
  660. max_length=150,
  661. editable=False
  662. )
  663. request_id = models.UUIDField(
  664. editable=False
  665. )
  666. action = models.PositiveSmallIntegerField(
  667. choices=OBJECTCHANGE_ACTION_CHOICES
  668. )
  669. changed_object_type = models.ForeignKey(
  670. to=ContentType,
  671. on_delete=models.PROTECT,
  672. related_name='+'
  673. )
  674. changed_object_id = models.PositiveIntegerField()
  675. changed_object = GenericForeignKey(
  676. ct_field='changed_object_type',
  677. fk_field='changed_object_id'
  678. )
  679. related_object_type = models.ForeignKey(
  680. to=ContentType,
  681. on_delete=models.PROTECT,
  682. related_name='+',
  683. blank=True,
  684. null=True
  685. )
  686. related_object_id = models.PositiveIntegerField(
  687. blank=True,
  688. null=True
  689. )
  690. related_object = GenericForeignKey(
  691. ct_field='related_object_type',
  692. fk_field='related_object_id'
  693. )
  694. object_repr = models.CharField(
  695. max_length=200,
  696. editable=False
  697. )
  698. object_data = JSONField(
  699. editable=False
  700. )
  701. csv_headers = [
  702. 'time', 'user', 'user_name', 'request_id', 'action', 'changed_object_type', 'changed_object_id',
  703. 'related_object_type', 'related_object_id', 'object_repr', 'object_data',
  704. ]
  705. class Meta:
  706. ordering = ['-time']
  707. def __str__(self):
  708. return '{} {} {} by {}'.format(
  709. self.changed_object_type,
  710. self.object_repr,
  711. self.get_action_display().lower(),
  712. self.user_name
  713. )
  714. def save(self, *args, **kwargs):
  715. # Record the user's name and the object's representation as static strings
  716. if not self.user_name:
  717. self.user_name = self.user.username
  718. if not self.object_repr:
  719. self.object_repr = str(self.changed_object)
  720. return super().save(*args, **kwargs)
  721. def get_absolute_url(self):
  722. return reverse('extras:objectchange', args=[self.pk])
  723. def to_csv(self):
  724. return (
  725. self.time,
  726. self.user,
  727. self.user_name,
  728. self.request_id,
  729. self.get_action_display(),
  730. self.changed_object_type,
  731. self.changed_object_id,
  732. self.related_object_type,
  733. self.related_object_id,
  734. self.object_repr,
  735. self.object_data,
  736. )
  737. #
  738. # Tags
  739. #
  740. # TODO: figure out a way around this circular import for ObjectChange
  741. from utilities.models import ChangeLoggedModel # noqa: E402
  742. class Tag(TagBase, ChangeLoggedModel):
  743. color = ColorField(
  744. default='9e9e9e'
  745. )
  746. comments = models.TextField(
  747. blank=True,
  748. default=''
  749. )
  750. def get_absolute_url(self):
  751. return reverse('extras:tag', args=[self.slug])
  752. class TaggedItem(GenericTaggedItemBase):
  753. tag = models.ForeignKey(
  754. to=Tag,
  755. related_name="%(app_label)s_%(class)s_items",
  756. on_delete=models.CASCADE
  757. )
  758. class Meta:
  759. index_together = (
  760. ("content_type", "object_id")
  761. )