Answer the question
In order to leave comments, you need to log in
How to add disabled attribute to input elements generated by MultipleChoiceField?
Hello!
I have a form with a MultipleChoiceField field. The form outputs data from the CHOICES tuple.
models.py:
class Requirement(models.Model):
code = models.UUIDField(_('Code'), primary_key=True, default=uuid.uuid4, editable=False)
symbol = models.CharField(_('Symbol'), max_length=250)
name = models.CharField(_('Name'), max_length=250)
CHOICES = (
('A', 'Name A'),
('B', 'Name B'),
('C', 'Name C'),
)
class RequirementAddForm(forms.ModelForm):
symbol = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple, choices=CHOICES,)
class Meta:
model = Requirement
fields = ('symbol',)
if form.is_valid():
list = dict(REQUIREMENTS_CHOICES) # {'C': 'Name C', 'A': 'Name A', 'B': 'Name B'}
symbols = form.cleaned_data.get('symbol') # ['A', 'B', 'C']
requirement = form.save(commit=False)
for symbol in symbols:
requirement.symbol = symbol
requirement.name = list[symbol]
requirement.save()
<ul id="id_symbol">
<li>
<label for="id_symbol_0" disabled="">
<input id="id_symbol_0" name="symbol" value="A" type="checkbox">Name A
</label>
</li>
<li>
<label for="id_symbol_1" disabled="">
<input id="id_symbol_1" name="symbol" value="B" type="checkbox">Name B
</label>
</li>
<li>
<label for="id_symbol_2" disabled="">
<input id="id_symbol_2" name="symbol" value="C" type="checkbox">Name C
</label>
</li>
</ul>
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question