widgets.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import json
  2. from django import forms
  3. from django.forms.utils import flatatt
  4. from ipam.choices import ServiceProtocolChoices
  5. __all__ = (
  6. 'PortMappingWidget',
  7. )
  8. class PortMappingWidget(forms.Widget):
  9. """
  10. Renders a dynamic set of (protocol, ports) rows. The rows are serialized to a JSON string held in a
  11. single hidden input (client-side JS keeps the hidden input in sync as rows are added/removed). Each
  12. row's ``ports`` value is a raw comma/range string (e.g. "80,443,8000-8010"); the server expands it.
  13. """
  14. template_name = 'ipam/widgets/port_mappings.html'
  15. # aria-* attributes which render_field_with_aria() sets per-field, and which must be copied onto the
  16. # row controls: the wrapping <div> isn't a form control, so assistive technology ignores them there.
  17. CONTROL_ATTRS = ('aria-describedby', 'aria-invalid')
  18. def id_for_label(self, id_):
  19. # The field's <label for="..."> must point at a real form control, not the wrapping <div> which
  20. # carries the widget's id. Target the first row's protocol <select>; the client-side widget keeps
  21. # this id on whichever row is first as rows are added and removed.
  22. return f'{id_}_protocol_0' if id_ else ''
  23. def get_context(self, name, value, attrs):
  24. attrs = attrs or {}
  25. rows = []
  26. if value:
  27. try:
  28. rows = json.loads(value)
  29. except (TypeError, ValueError):
  30. rows = []
  31. # Re-rendering an invalid bound form hands us back the raw POST value, which need not be the list
  32. # of {protocol, ports} objects the JS produces: a crafted payload of e.g. `5` or `{"a": 1}` parses
  33. # as valid JSON but would break the template's row loop. Discard anything of the wrong shape and
  34. # fall through to the blank row below.
  35. if not isinstance(rows, list) or not all(isinstance(row, dict) for row in rows):
  36. rows = []
  37. # Always render at least one (blank) row so the entry fields are visible on an empty form
  38. if not rows:
  39. rows = [{'protocol': '', 'ports': ''}]
  40. return {
  41. 'widget': {
  42. 'name': name,
  43. 'value': value or '[]',
  44. 'rows': rows,
  45. 'attrs': attrs,
  46. 'label_id': self.id_for_label(attrs.get('id')),
  47. 'control_attrs': flatatt({
  48. key: value for key, value in attrs.items() if key in self.CONTROL_ATTRS
  49. }),
  50. },
  51. 'protocol_choices': list(ServiceProtocolChoices),
  52. }
  53. def value_from_datadict(self, data, files, name):
  54. return data.get(name)