models.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868
  1. from __future__ import unicode_literals
  2. from collections import OrderedDict
  3. from datetime import date
  4. import json
  5. import graphviz
  6. from django.contrib.auth.models import User
  7. from django.contrib.contenttypes.fields import GenericForeignKey
  8. from django.contrib.contenttypes.models import ContentType
  9. from django.contrib.postgres.fields import JSONField
  10. from django.core.urlresolvers import reverse
  11. from django.core.validators import ValidationError
  12. from django.db import models
  13. from django.db.models import Q
  14. from django.http import HttpResponse
  15. from django.template import Template, Context
  16. from django.utils.encoding import python_2_unicode_compatible
  17. from django.utils.safestring import mark_safe
  18. from dcim.constants import CONNECTION_STATUS_CONNECTED
  19. from utilities.utils import foreground_color
  20. from .constants import *
  21. #
  22. # Webhooks
  23. #
  24. @python_2_unicode_compatible
  25. class Webhook(models.Model):
  26. """
  27. A Webhook defines a request that will be sent to a remote application when an object is created, updated, and/or
  28. delete in NetBox. The request will contain a representation of the object, which the remote application can act on.
  29. Each Webhook can be limited to firing only on certain actions or certain object types.
  30. """
  31. obj_type = models.ManyToManyField(
  32. to=ContentType,
  33. related_name='webhooks',
  34. verbose_name='Object types',
  35. limit_choices_to={'model__in': WEBHOOK_MODELS},
  36. help_text="The object(s) to which this Webhook applies."
  37. )
  38. name = models.CharField(
  39. max_length=150,
  40. unique=True
  41. )
  42. type_create = models.BooleanField(
  43. default=False,
  44. help_text="Call this webhook when a matching object is created."
  45. )
  46. type_update = models.BooleanField(
  47. default=False,
  48. help_text="Call this webhook when a matching object is updated."
  49. )
  50. type_delete = models.BooleanField(
  51. default=False,
  52. help_text="Call this webhook when a matching object is deleted."
  53. )
  54. payload_url = models.CharField(
  55. max_length=500,
  56. verbose_name='URL',
  57. help_text="A POST will be sent to this URL when the webhook is called."
  58. )
  59. http_content_type = models.PositiveSmallIntegerField(
  60. choices=WEBHOOK_CT_CHOICES,
  61. default=WEBHOOK_CT_JSON
  62. )
  63. secret = models.CharField(
  64. max_length=255,
  65. blank=True,
  66. help_text="When provided, the request will include a 'X-Hook-Signature' "
  67. "header containing a HMAC hex digest of the payload body using "
  68. "the secret as the key. The secret is not transmitted in "
  69. "the request."
  70. )
  71. enabled = models.BooleanField(
  72. default=True
  73. )
  74. ssl_verification = models.BooleanField(
  75. default=True,
  76. help_text="Enable SSL certificate verification. Disable with caution!"
  77. )
  78. class Meta:
  79. unique_together = ('payload_url', 'type_create', "type_update", "type_delete",)
  80. def __str__(self):
  81. return self.name
  82. def clean(self):
  83. """
  84. Validate model
  85. """
  86. if not self.type_create and not self.type_delete and not self.type_update:
  87. raise ValidationError(
  88. "You must select at least one type: create, update, and/or delete."
  89. )
  90. #
  91. # Custom fields
  92. #
  93. class CustomFieldModel(object):
  94. def cf(self):
  95. """
  96. Name-based CustomFieldValue accessor for use in templates
  97. """
  98. if not hasattr(self, 'get_custom_fields'):
  99. return dict()
  100. return {field.name: value for field, value in self.get_custom_fields().items()}
  101. def get_custom_fields(self):
  102. """
  103. Return a dictionary of custom fields for a single object in the form {<field>: value}.
  104. """
  105. # Find all custom fields applicable to this type of object
  106. content_type = ContentType.objects.get_for_model(self)
  107. fields = CustomField.objects.filter(obj_type=content_type)
  108. # If the object exists, populate its custom fields with values
  109. if hasattr(self, 'pk'):
  110. values = CustomFieldValue.objects.filter(obj_type=content_type, obj_id=self.pk).select_related('field')
  111. values_dict = {cfv.field_id: cfv.value for cfv in values}
  112. return OrderedDict([(field, values_dict.get(field.pk)) for field in fields])
  113. else:
  114. return OrderedDict([(field, None) for field in fields])
  115. @python_2_unicode_compatible
  116. class CustomField(models.Model):
  117. obj_type = models.ManyToManyField(
  118. to=ContentType,
  119. related_name='custom_fields',
  120. verbose_name='Object(s)',
  121. limit_choices_to={'model__in': CUSTOMFIELD_MODELS},
  122. help_text='The object(s) to which this field applies.'
  123. )
  124. type = models.PositiveSmallIntegerField(
  125. choices=CUSTOMFIELD_TYPE_CHOICES,
  126. default=CF_TYPE_TEXT
  127. )
  128. name = models.CharField(
  129. max_length=50,
  130. unique=True
  131. )
  132. label = models.CharField(
  133. max_length=50,
  134. blank=True,
  135. help_text='Name of the field as displayed to users (if not provided, '
  136. 'the field\'s name will be used)'
  137. )
  138. description = models.CharField(
  139. max_length=100,
  140. blank=True
  141. )
  142. required = models.BooleanField(
  143. default=False,
  144. help_text='If true, this field is required when creating new objects '
  145. 'or editing an existing object.'
  146. )
  147. filter_logic = models.PositiveSmallIntegerField(
  148. choices=CF_FILTER_CHOICES,
  149. default=CF_FILTER_LOOSE,
  150. help_text='Loose matches any instance of a given string; exact '
  151. 'matches the entire field.'
  152. )
  153. default = models.CharField(
  154. max_length=100,
  155. blank=True,
  156. help_text='Default value for the field. Use "true" or "false" for '
  157. 'booleans. N/A for selection fields.'
  158. )
  159. weight = models.PositiveSmallIntegerField(
  160. default=100,
  161. help_text='Fields with higher weights appear lower in a form.'
  162. )
  163. class Meta:
  164. ordering = ['weight', 'name']
  165. def __str__(self):
  166. return self.label or self.name.replace('_', ' ').capitalize()
  167. def serialize_value(self, value):
  168. """
  169. Serialize the given value to a string suitable for storage as a CustomFieldValue
  170. """
  171. if value is None:
  172. return ''
  173. if self.type == CF_TYPE_BOOLEAN:
  174. return str(int(bool(value)))
  175. if self.type == CF_TYPE_DATE:
  176. # Could be date/datetime object or string
  177. try:
  178. return value.strftime('%Y-%m-%d')
  179. except AttributeError:
  180. return value
  181. if self.type == CF_TYPE_SELECT:
  182. # Could be ModelChoiceField or TypedChoiceField
  183. return str(value.id) if hasattr(value, 'id') else str(value)
  184. return value
  185. def deserialize_value(self, serialized_value):
  186. """
  187. Convert a string into the object it represents depending on the type of field
  188. """
  189. if serialized_value == '':
  190. return None
  191. if self.type == CF_TYPE_INTEGER:
  192. return int(serialized_value)
  193. if self.type == CF_TYPE_BOOLEAN:
  194. return bool(int(serialized_value))
  195. if self.type == CF_TYPE_DATE:
  196. # Read date as YYYY-MM-DD
  197. return date(*[int(n) for n in serialized_value.split('-')])
  198. if self.type == CF_TYPE_SELECT:
  199. return self.choices.get(pk=int(serialized_value))
  200. return serialized_value
  201. @python_2_unicode_compatible
  202. class CustomFieldValue(models.Model):
  203. field = models.ForeignKey(
  204. to='extras.CustomField',
  205. on_delete=models.CASCADE,
  206. related_name='values'
  207. )
  208. obj_type = models.ForeignKey(
  209. to=ContentType,
  210. on_delete=models.PROTECT,
  211. related_name='+'
  212. )
  213. obj_id = models.PositiveIntegerField()
  214. obj = GenericForeignKey(
  215. ct_field='obj_type',
  216. fk_field='obj_id'
  217. )
  218. serialized_value = models.CharField(
  219. max_length=255
  220. )
  221. class Meta:
  222. ordering = ['obj_type', 'obj_id']
  223. unique_together = ['field', 'obj_type', 'obj_id']
  224. def __str__(self):
  225. return '{} {}'.format(self.obj, self.field)
  226. @property
  227. def value(self):
  228. return self.field.deserialize_value(self.serialized_value)
  229. @value.setter
  230. def value(self, value):
  231. self.serialized_value = self.field.serialize_value(value)
  232. def save(self, *args, **kwargs):
  233. # Delete this object if it no longer has a value to store
  234. if self.pk and self.value is None:
  235. self.delete()
  236. else:
  237. super(CustomFieldValue, self).save(*args, **kwargs)
  238. @python_2_unicode_compatible
  239. class CustomFieldChoice(models.Model):
  240. field = models.ForeignKey(
  241. to='extras.CustomField',
  242. on_delete=models.CASCADE,
  243. related_name='choices',
  244. limit_choices_to={'type': CF_TYPE_SELECT}
  245. )
  246. value = models.CharField(
  247. max_length=100
  248. )
  249. weight = models.PositiveSmallIntegerField(
  250. default=100,
  251. help_text='Higher weights appear lower in the list'
  252. )
  253. class Meta:
  254. ordering = ['field', 'weight', 'value']
  255. unique_together = ['field', 'value']
  256. def __str__(self):
  257. return self.value
  258. def clean(self):
  259. if self.field.type != CF_TYPE_SELECT:
  260. raise ValidationError("Custom field choices can only be assigned to selection fields.")
  261. def delete(self, using=None, keep_parents=False):
  262. # When deleting a CustomFieldChoice, delete all CustomFieldValues which point to it
  263. pk = self.pk
  264. super(CustomFieldChoice, self).delete(using, keep_parents)
  265. CustomFieldValue.objects.filter(field__type=CF_TYPE_SELECT, serialized_value=str(pk)).delete()
  266. #
  267. # Graphs
  268. #
  269. @python_2_unicode_compatible
  270. class Graph(models.Model):
  271. type = models.PositiveSmallIntegerField(
  272. choices=GRAPH_TYPE_CHOICES
  273. )
  274. weight = models.PositiveSmallIntegerField(
  275. default=1000
  276. )
  277. name = models.CharField(
  278. max_length=100,
  279. verbose_name='Name'
  280. )
  281. source = models.CharField(
  282. max_length=500,
  283. verbose_name='Source URL'
  284. )
  285. link = models.URLField(
  286. blank=True,
  287. verbose_name='Link URL'
  288. )
  289. class Meta:
  290. ordering = ['type', 'weight', 'name']
  291. def __str__(self):
  292. return self.name
  293. def embed_url(self, obj):
  294. template = Template(self.source)
  295. return template.render(Context({'obj': obj}))
  296. def embed_link(self, obj):
  297. if self.link is None:
  298. return ''
  299. template = Template(self.link)
  300. return template.render(Context({'obj': obj}))
  301. #
  302. # Export templates
  303. #
  304. @python_2_unicode_compatible
  305. class ExportTemplate(models.Model):
  306. content_type = models.ForeignKey(
  307. to=ContentType,
  308. on_delete=models.CASCADE,
  309. limit_choices_to={'model__in': EXPORTTEMPLATE_MODELS}
  310. )
  311. name = models.CharField(
  312. max_length=100
  313. )
  314. description = models.CharField(
  315. max_length=200,
  316. blank=True
  317. )
  318. template_code = models.TextField()
  319. mime_type = models.CharField(
  320. max_length=15,
  321. blank=True
  322. )
  323. file_extension = models.CharField(
  324. max_length=15,
  325. blank=True
  326. )
  327. class Meta:
  328. ordering = ['content_type', 'name']
  329. unique_together = [
  330. ['content_type', 'name']
  331. ]
  332. def __str__(self):
  333. return '{}: {}'.format(self.content_type, self.name)
  334. def render_to_response(self, queryset):
  335. """
  336. Render the template to an HTTP response, delivered as a named file attachment
  337. """
  338. template = Template(self.template_code)
  339. mime_type = 'text/plain' if not self.mime_type else self.mime_type
  340. output = template.render(Context({'queryset': queryset}))
  341. # Replace CRLF-style line terminators
  342. output = output.replace('\r\n', '\n')
  343. # Build the response
  344. response = HttpResponse(output, content_type=mime_type)
  345. filename = 'netbox_{}{}'.format(
  346. queryset.model._meta.verbose_name_plural,
  347. '.{}'.format(self.file_extension) if self.file_extension else ''
  348. )
  349. response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
  350. return response
  351. #
  352. # Topology maps
  353. #
  354. @python_2_unicode_compatible
  355. class TopologyMap(models.Model):
  356. name = models.CharField(
  357. max_length=50,
  358. unique=True
  359. )
  360. slug = models.SlugField(
  361. unique=True
  362. )
  363. type = models.PositiveSmallIntegerField(
  364. choices=TOPOLOGYMAP_TYPE_CHOICES,
  365. default=TOPOLOGYMAP_TYPE_NETWORK
  366. )
  367. site = models.ForeignKey(
  368. to='dcim.Site',
  369. on_delete=models.CASCADE,
  370. related_name='topology_maps',
  371. blank=True,
  372. null=True
  373. )
  374. device_patterns = models.TextField(
  375. help_text='Identify devices to include in the diagram using regular '
  376. 'expressions, one per line. Each line will result in a new '
  377. 'tier of the drawing. Separate multiple regexes within a '
  378. 'line using semicolons. Devices will be rendered in the '
  379. 'order they are defined.'
  380. )
  381. description = models.CharField(
  382. max_length=100,
  383. blank=True
  384. )
  385. class Meta:
  386. ordering = ['name']
  387. def __str__(self):
  388. return self.name
  389. @property
  390. def device_sets(self):
  391. if not self.device_patterns:
  392. return None
  393. return [line.strip() for line in self.device_patterns.split('\n')]
  394. def render(self, img_format='png'):
  395. from dcim.models import Device
  396. # Construct the graph
  397. if self.type == TOPOLOGYMAP_TYPE_NETWORK:
  398. G = graphviz.Graph
  399. else:
  400. G = graphviz.Digraph
  401. self.graph = G()
  402. self.graph.graph_attr['ranksep'] = '1'
  403. seen = set()
  404. for i, device_set in enumerate(self.device_sets):
  405. subgraph = G(name='sg{}'.format(i))
  406. subgraph.graph_attr['rank'] = 'same'
  407. subgraph.graph_attr['directed'] = 'true'
  408. # Add a pseudonode for each device_set to enforce hierarchical layout
  409. subgraph.node('set{}'.format(i), label='', shape='none', width='0')
  410. if i:
  411. self.graph.edge('set{}'.format(i - 1), 'set{}'.format(i), style='invis')
  412. # Add each device to the graph
  413. devices = []
  414. for query in device_set.strip(';').split(';'): # Split regexes on semicolons
  415. devices += Device.objects.filter(name__regex=query).select_related('device_role')
  416. # Remove duplicate devices
  417. devices = [d for d in devices if d.id not in seen]
  418. seen.update([d.id for d in devices])
  419. for d in devices:
  420. bg_color = '#{}'.format(d.device_role.color)
  421. fg_color = '#{}'.format(foreground_color(d.device_role.color))
  422. subgraph.node(d.name, style='filled', fillcolor=bg_color, fontcolor=fg_color, fontname='sans')
  423. # Add an invisible connection to each successive device in a set to enforce horizontal order
  424. for j in range(0, len(devices) - 1):
  425. subgraph.edge(devices[j].name, devices[j + 1].name, style='invis')
  426. self.graph.subgraph(subgraph)
  427. # Compile list of all devices
  428. device_superset = Q()
  429. for device_set in self.device_sets:
  430. for query in device_set.split(';'): # Split regexes on semicolons
  431. device_superset = device_superset | Q(name__regex=query)
  432. devices = Device.objects.filter(*(device_superset,))
  433. # Draw edges depending on graph type
  434. if self.type == TOPOLOGYMAP_TYPE_NETWORK:
  435. self.add_network_connections(devices)
  436. elif self.type == TOPOLOGYMAP_TYPE_CONSOLE:
  437. self.add_console_connections(devices)
  438. elif self.type == TOPOLOGYMAP_TYPE_POWER:
  439. self.add_power_connections(devices)
  440. return self.graph.pipe(format=img_format)
  441. def add_network_connections(self, devices):
  442. from circuits.models import CircuitTermination
  443. from dcim.models import InterfaceConnection
  444. # Add all interface connections to the graph
  445. connections = InterfaceConnection.objects.filter(
  446. interface_a__device__in=devices, interface_b__device__in=devices
  447. )
  448. for c in connections:
  449. style = 'solid' if c.connection_status == CONNECTION_STATUS_CONNECTED else 'dashed'
  450. self.graph.edge(c.interface_a.device.name, c.interface_b.device.name, style=style)
  451. # Add all circuits to the graph
  452. for termination in CircuitTermination.objects.filter(term_side='A', interface__device__in=devices):
  453. peer_termination = termination.get_peer_termination()
  454. if (peer_termination is not None and peer_termination.interface is not None and
  455. peer_termination.interface.device in devices):
  456. self.graph.edge(termination.interface.device.name, peer_termination.interface.device.name, color='blue')
  457. def add_console_connections(self, devices):
  458. from dcim.models import ConsolePort
  459. # Add all console connections to the graph
  460. console_ports = ConsolePort.objects.filter(device__in=devices, cs_port__device__in=devices)
  461. for cp in console_ports:
  462. style = 'solid' if cp.connection_status == CONNECTION_STATUS_CONNECTED else 'dashed'
  463. self.graph.edge(cp.cs_port.device.name, cp.device.name, style=style)
  464. def add_power_connections(self, devices):
  465. from dcim.models import PowerPort
  466. # Add all power connections to the graph
  467. power_ports = PowerPort.objects.filter(device__in=devices, power_outlet__device__in=devices)
  468. for pp in power_ports:
  469. style = 'solid' if pp.connection_status == CONNECTION_STATUS_CONNECTED else 'dashed'
  470. self.graph.edge(pp.power_outlet.device.name, pp.device.name, style=style)
  471. #
  472. # Image attachments
  473. #
  474. def image_upload(instance, filename):
  475. path = 'image-attachments/'
  476. # Rename the file to the provided name, if any. Attempt to preserve the file extension.
  477. extension = filename.rsplit('.')[-1].lower()
  478. if instance.name and extension in ['bmp', 'gif', 'jpeg', 'jpg', 'png']:
  479. filename = '.'.join([instance.name, extension])
  480. elif instance.name:
  481. filename = instance.name
  482. return '{}{}_{}_{}'.format(path, instance.content_type.name, instance.object_id, filename)
  483. @python_2_unicode_compatible
  484. class ImageAttachment(models.Model):
  485. """
  486. An uploaded image which is associated with an object.
  487. """
  488. content_type = models.ForeignKey(
  489. to=ContentType,
  490. on_delete=models.CASCADE
  491. )
  492. object_id = models.PositiveIntegerField()
  493. parent = GenericForeignKey(
  494. ct_field='content_type',
  495. fk_field='object_id'
  496. )
  497. image = models.ImageField(
  498. upload_to=image_upload,
  499. height_field='image_height',
  500. width_field='image_width'
  501. )
  502. image_height = models.PositiveSmallIntegerField()
  503. image_width = models.PositiveSmallIntegerField()
  504. name = models.CharField(
  505. max_length=50,
  506. blank=True
  507. )
  508. created = models.DateTimeField(
  509. auto_now_add=True
  510. )
  511. class Meta:
  512. ordering = ['name']
  513. def __str__(self):
  514. if self.name:
  515. return self.name
  516. filename = self.image.name.rsplit('/', 1)[-1]
  517. return filename.split('_', 2)[2]
  518. def delete(self, *args, **kwargs):
  519. _name = self.image.name
  520. super(ImageAttachment, self).delete(*args, **kwargs)
  521. # Delete file from disk
  522. self.image.delete(save=False)
  523. # Deleting the file erases its name. We restore the image's filename here in case we still need to reference it
  524. # before the request finishes. (For example, to display a message indicating the ImageAttachment was deleted.)
  525. self.image.name = _name
  526. @property
  527. def size(self):
  528. """
  529. Wrapper around `image.size` to suppress an OSError in case the file is inaccessible.
  530. """
  531. try:
  532. return self.image.size
  533. except OSError:
  534. return None
  535. #
  536. # Report results
  537. #
  538. class ReportResult(models.Model):
  539. """
  540. This model stores the results from running a user-defined report.
  541. """
  542. report = models.CharField(
  543. max_length=255,
  544. unique=True
  545. )
  546. created = models.DateTimeField(
  547. auto_now_add=True
  548. )
  549. user = models.ForeignKey(
  550. to=User,
  551. on_delete=models.SET_NULL,
  552. related_name='+',
  553. blank=True,
  554. null=True
  555. )
  556. failed = models.BooleanField()
  557. data = JSONField()
  558. class Meta:
  559. ordering = ['report']
  560. #
  561. # Change logging
  562. #
  563. @python_2_unicode_compatible
  564. class ObjectChange(models.Model):
  565. """
  566. Record a change to an object and the user account associated with that change. A change record may optionally
  567. indicate an object related to the one being changed. For example, a change to an interface may also indicate the
  568. parent device. This will ensure changes made to component models appear in the parent model's changelog.
  569. """
  570. time = models.DateTimeField(
  571. auto_now_add=True,
  572. editable=False
  573. )
  574. user = models.ForeignKey(
  575. to=User,
  576. on_delete=models.SET_NULL,
  577. related_name='changes',
  578. blank=True,
  579. null=True
  580. )
  581. user_name = models.CharField(
  582. max_length=150,
  583. editable=False
  584. )
  585. request_id = models.UUIDField(
  586. editable=False
  587. )
  588. action = models.PositiveSmallIntegerField(
  589. choices=OBJECTCHANGE_ACTION_CHOICES
  590. )
  591. changed_object_type = models.ForeignKey(
  592. to=ContentType,
  593. on_delete=models.PROTECT,
  594. related_name='+'
  595. )
  596. changed_object_id = models.PositiveIntegerField()
  597. changed_object = GenericForeignKey(
  598. ct_field='changed_object_type',
  599. fk_field='changed_object_id'
  600. )
  601. related_object_type = models.ForeignKey(
  602. to=ContentType,
  603. on_delete=models.PROTECT,
  604. related_name='+',
  605. blank=True,
  606. null=True
  607. )
  608. related_object_id = models.PositiveIntegerField(
  609. blank=True,
  610. null=True
  611. )
  612. related_object = GenericForeignKey(
  613. ct_field='related_object_type',
  614. fk_field='related_object_id'
  615. )
  616. object_repr = models.CharField(
  617. max_length=200,
  618. editable=False
  619. )
  620. object_data = JSONField(
  621. editable=False
  622. )
  623. serializer = 'extras.api.serializers.ObjectChangeSerializer'
  624. csv_headers = [
  625. 'time', 'user', 'user_name', 'request_id', 'action', 'changed_object_type', 'changed_object_id',
  626. 'related_object_type', 'related_object_id', 'object_repr', 'object_data',
  627. ]
  628. class Meta:
  629. ordering = ['-time']
  630. def __str__(self):
  631. return '{} {} {} by {}'.format(
  632. self.changed_object_type,
  633. self.object_repr,
  634. self.get_action_display().lower(),
  635. self.user_name
  636. )
  637. def save(self, *args, **kwargs):
  638. # Record the user's name and the object's representation as static strings
  639. self.user_name = self.user.username
  640. self.object_repr = str(self.changed_object)
  641. return super(ObjectChange, self).save(*args, **kwargs)
  642. def get_absolute_url(self):
  643. return reverse('extras:objectchange', args=[self.pk])
  644. def to_csv(self):
  645. return (
  646. self.time,
  647. self.user,
  648. self.user_name,
  649. self.request_id,
  650. self.get_action_display(),
  651. self.changed_object_type,
  652. self.changed_object_id,
  653. self.related_object_type,
  654. self.related_object_id,
  655. self.object_repr,
  656. self.object_data,
  657. )
  658. @property
  659. def object_data_pretty(self):
  660. return json.dumps(self.object_data, indent=4, sort_keys=True)
  661. #
  662. # User actions
  663. #
  664. class UserActionManager(models.Manager):
  665. # Actions affecting a single object
  666. def log_action(self, user, obj, action, message):
  667. self.model.objects.create(
  668. content_type=ContentType.objects.get_for_model(obj),
  669. object_id=obj.pk,
  670. user=user,
  671. action=action,
  672. message=message,
  673. )
  674. def log_create(self, user, obj, message=''):
  675. self.log_action(user, obj, ACTION_CREATE, message)
  676. def log_edit(self, user, obj, message=''):
  677. self.log_action(user, obj, ACTION_EDIT, message)
  678. def log_delete(self, user, obj, message=''):
  679. self.log_action(user, obj, ACTION_DELETE, message)
  680. # Actions affecting multiple objects
  681. def log_bulk_action(self, user, content_type, action, message):
  682. self.model.objects.create(
  683. content_type=content_type,
  684. user=user,
  685. action=action,
  686. message=message,
  687. )
  688. def log_import(self, user, content_type, message=''):
  689. self.log_bulk_action(user, content_type, ACTION_IMPORT, message)
  690. def log_bulk_create(self, user, content_type, message=''):
  691. self.log_bulk_action(user, content_type, ACTION_BULK_CREATE, message)
  692. def log_bulk_edit(self, user, content_type, message=''):
  693. self.log_bulk_action(user, content_type, ACTION_BULK_EDIT, message)
  694. def log_bulk_delete(self, user, content_type, message=''):
  695. self.log_bulk_action(user, content_type, ACTION_BULK_DELETE, message)
  696. @python_2_unicode_compatible
  697. class UserAction(models.Model):
  698. """
  699. A record of an action (add, edit, or delete) performed on an object by a User.
  700. """
  701. time = models.DateTimeField(
  702. auto_now_add=True,
  703. editable=False
  704. )
  705. user = models.ForeignKey(
  706. to=User,
  707. on_delete=models.CASCADE,
  708. related_name='actions'
  709. )
  710. content_type = models.ForeignKey(
  711. to=ContentType,
  712. on_delete=models.CASCADE
  713. )
  714. object_id = models.PositiveIntegerField(
  715. blank=True,
  716. null=True
  717. )
  718. action = models.PositiveSmallIntegerField(
  719. choices=ACTION_CHOICES
  720. )
  721. message = models.TextField(
  722. blank=True
  723. )
  724. objects = UserActionManager()
  725. class Meta:
  726. ordering = ['-time']
  727. def __str__(self):
  728. if self.message:
  729. return '{} {}'.format(self.user, self.message)
  730. return '{} {} {}'.format(self.user, self.get_action_display(), self.content_type)
  731. def icon(self):
  732. if self.action in [ACTION_CREATE, ACTION_BULK_CREATE, ACTION_IMPORT]:
  733. return mark_safe('<i class="glyphicon glyphicon-plus text-success"></i>')
  734. elif self.action in [ACTION_EDIT, ACTION_BULK_EDIT]:
  735. return mark_safe('<i class="glyphicon glyphicon-pencil text-warning"></i>')
  736. elif self.action in [ACTION_DELETE, ACTION_BULK_DELETE]:
  737. return mark_safe('<i class="glyphicon glyphicon-remove text-danger"></i>')
  738. else:
  739. return ''