widgets.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. import json
  2. from django import forms
  3. from django.conf import settings
  4. from django.contrib.postgres.forms import SimpleArrayField
  5. from utilities.choices import ColorChoices
  6. from .utils import add_blank_choice, parse_numeric_range
  7. __all__ = (
  8. 'APISelect',
  9. 'APISelectMultiple',
  10. 'BulkEditNullBooleanSelect',
  11. 'ColorSelect',
  12. 'ContentTypeSelect',
  13. 'DatePicker',
  14. 'DateTimePicker',
  15. 'NumericArrayField',
  16. 'SelectWithDisabled',
  17. 'SelectWithPK',
  18. 'SlugWidget',
  19. 'SmallTextarea',
  20. 'StaticSelect2',
  21. 'StaticSelect2Multiple',
  22. 'TimePicker',
  23. )
  24. class SmallTextarea(forms.Textarea):
  25. """
  26. Subclass used for rendering a smaller textarea element.
  27. """
  28. pass
  29. class SlugWidget(forms.TextInput):
  30. """
  31. Subclass TextInput and add a slug regeneration button next to the form field.
  32. """
  33. template_name = 'widgets/sluginput.html'
  34. class ColorSelect(forms.Select):
  35. """
  36. Extends the built-in Select widget to colorize each <option>.
  37. """
  38. option_template_name = 'widgets/colorselect_option.html'
  39. def __init__(self, *args, **kwargs):
  40. kwargs['choices'] = add_blank_choice(ColorChoices)
  41. super().__init__(*args, **kwargs)
  42. self.attrs['class'] = 'netbox-select2-color-picker'
  43. class BulkEditNullBooleanSelect(forms.NullBooleanSelect):
  44. """
  45. A Select widget for NullBooleanFields
  46. """
  47. def __init__(self, *args, **kwargs):
  48. super().__init__(*args, **kwargs)
  49. # Override the built-in choice labels
  50. self.choices = (
  51. ('1', '---------'),
  52. ('2', 'Yes'),
  53. ('3', 'No'),
  54. )
  55. self.attrs['class'] = 'netbox-select2-static'
  56. class SelectWithDisabled(forms.Select):
  57. """
  58. Modified the stock Select widget to accept choices using a dict() for a label. The dict for each option must include
  59. 'label' (string) and 'disabled' (boolean).
  60. """
  61. option_template_name = 'widgets/selectwithdisabled_option.html'
  62. class StaticSelect2(SelectWithDisabled):
  63. """
  64. A static <select> form widget using the Select2 library.
  65. """
  66. def __init__(self, *args, **kwargs):
  67. super().__init__(*args, **kwargs)
  68. self.attrs['class'] = 'netbox-select2-static'
  69. class StaticSelect2Multiple(StaticSelect2, forms.SelectMultiple):
  70. def __init__(self, *args, **kwargs):
  71. super().__init__(*args, **kwargs)
  72. self.attrs['data-multiple'] = 1
  73. class SelectWithPK(StaticSelect2):
  74. """
  75. Include the primary key of each option in the option label (e.g. "Router7 (4721)").
  76. """
  77. option_template_name = 'widgets/select_option_with_pk.html'
  78. class ContentTypeSelect(StaticSelect2):
  79. """
  80. Appends an `api-value` attribute equal to the slugified model name for each ContentType. For example:
  81. <option value="37" api-value="console-server-port">console server port</option>
  82. This attribute can be used to reference the relevant API endpoint for a particular ContentType.
  83. """
  84. option_template_name = 'widgets/select_contenttype.html'
  85. class NumericArrayField(SimpleArrayField):
  86. def to_python(self, value):
  87. value = ','.join([str(n) for n in parse_numeric_range(value)])
  88. return super().to_python(value)
  89. class APISelect(SelectWithDisabled):
  90. """
  91. A select widget populated via an API call
  92. :param api_url: API endpoint URL. Required if not set automatically by the parent field.
  93. :param full: Omit brief=true when fetching REST API results
  94. """
  95. def __init__(self, api_url=None, full=False, *args, **kwargs):
  96. super().__init__(*args, **kwargs)
  97. self.attrs['class'] = 'netbox-select2-api'
  98. if api_url:
  99. self.attrs['data-url'] = '/{}{}'.format(settings.BASE_PATH, api_url.lstrip('/')) # Inject BASE_PATH
  100. if full:
  101. self.attrs['data-full'] = full
  102. def add_query_param(self, name, value):
  103. """
  104. Add details for an additional query param in the form of a data-* JSON-encoded list attribute.
  105. :param name: The name of the query param
  106. :param value: The value of the query param
  107. """
  108. key = f'data-additional-query-param-{name}'
  109. values = json.loads(self.attrs.get(key, '[]'))
  110. if type(value) is list:
  111. values.extend(value)
  112. else:
  113. values.append(value)
  114. self.attrs[key] = json.dumps(values)
  115. class APISelectMultiple(APISelect, forms.SelectMultiple):
  116. def __init__(self, *args, **kwargs):
  117. super().__init__(*args, **kwargs)
  118. self.attrs['data-multiple'] = 1
  119. class DatePicker(forms.TextInput):
  120. """
  121. Date picker using Flatpickr.
  122. """
  123. def __init__(self, *args, **kwargs):
  124. super().__init__(*args, **kwargs)
  125. self.attrs['class'] = 'date-picker'
  126. self.attrs['placeholder'] = 'YYYY-MM-DD'
  127. class DateTimePicker(forms.TextInput):
  128. """
  129. DateTime picker using Flatpickr.
  130. """
  131. def __init__(self, *args, **kwargs):
  132. super().__init__(*args, **kwargs)
  133. self.attrs['class'] = 'datetime-picker'
  134. self.attrs['placeholder'] = 'YYYY-MM-DD hh:mm:ss'
  135. class TimePicker(forms.TextInput):
  136. """
  137. Time picker using Flatpickr.
  138. """
  139. def __init__(self, *args, **kwargs):
  140. super().__init__(*args, **kwargs)
  141. self.attrs['class'] = 'time-picker'
  142. self.attrs['placeholder'] = 'hh:mm:ss'