Skip to content

Instantly share code, notes, and snippets.

@smithdc1
Last active April 13, 2020 12:18
Show Gist options
  • Save smithdc1/55cb50eab524bcaf8c45bc89f31c064b to your computer and use it in GitHub Desktop.
Save smithdc1/55cb50eab524bcaf8c45bc89f31c064b to your computer and use it in GitHub Desktop.
Add `required` attribute to MultiValueFields
def __init__(self, fields, *, require_all_fields=True, **kwargs):
self.require_all_fields = require_all_fields
super().__init__(**kwargs)
# We have two sets of widgets. Each field in fields has a widget whilst self.widget is probably our `MultiWidget`
# We're interested in the MultiWidget as this is what is rendered.
# Let's loop over fields and the MultiWidget and set required on the subwidgets.
for field, widget in zip(fields, self.widget.widgets):
field.error_messages.setdefault('incomplete',
self.error_messages['incomplete'])
if self.disabled:
field.disabled = True
# still to agree actual logic for the following section.
if (self.required and (self.require_all_fields or field.required)) or (
not self.required and not self.require_all_fields and field.required
):
field.required = widget.is_required = True
else:
field.required = widget.is_required = False
self.fields = fields
def get_context(self, name, value, attrs):
context = super().get_context(name, value, attrs)
if self.is_localized:
for widget in self.widgets:
widget.is_localized = self.is_localized
# value is a list of values, each corresponding to a widget
# in self.widgets.
if not isinstance(value, list):
value = self.decompress(value)
final_attrs = context['widget']['attrs']
input_type = final_attrs.pop('type', None)
id_ = final_attrs.get('id')
subwidgets = []
for i, (widget_name, widget) in enumerate(zip(self.widgets_names, self.widgets)):
if input_type is not None:
widget.input_type = input_type
widget_name = name + widget_name
try:
widget_value = value[i]
except IndexError:
widget_value = None
if id_:
widget_attrs = final_attrs.copy()
widget_attrs['id'] = '%s_%s' % (id_, i)
else:
widget_attrs = final_attrs
# Now that each subwidget has is_required set properly, lets add the attribute to the context here
if widget.is_required and not widget.is_hidden:
widget_attrs['required'] = True
subwidgets.append(widget.get_context(widget_name, widget_value, widget_attrs)['widget'])
context['widget']['subwidgets'] = subwidgets
return context
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment