'How is the "required" attribute dynamically set on a MultiWidget?
There are 4x TextInput elements that comprise a MultiWidget. Only the first TextInput requires the required attribute. Yet required is being set on all four elements.
Form.use_required_attribute is not suitable for my case due it's binary nature; either values for all form fields are required or not. I've set required=False to every possible place where it's potentially warranted, but I'm still not getting the desired result.
How can I get just the first TextInput set to required?
class MultiTagWidget(MultiWidget):
def __init__(self, *args, **kwargs):
widgets = [TextInput(attrs=kwargs['attrs']) for i in range(4)]
super().__init__(widgets, *args, **kwargs)
def decompress(self, value):
if value:
return value.split("_")
return ""
class TagField(MultiValueField):
def __init__(self, *args, **kwargs):
fields = []
for i in range(4):
field = CharField(**{
"min_length": 1, "max_length": 25, "validators":[
RegexValidator("[<>`':;,.\"]", inverse_match=True)
]
})
if i == 0:
field.error_messages = {
'incomplete': "Provide at least 1 tag for your question"
}
field.required = True
else:
field.required = False
fields.append(field)
super().__init__(fields, *args, **kwargs)
def compress(self, data_list):
data_list = "_".join(list(set([tag.lower().strip() for tag in data_list])))
return data_list
tags = TagField(
widget=MultiTagWidget(
attrs={"required": False}
), require_all_fields=False,
help_text="Add up to 4 tags for your question"
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
