Answer the question
In order to leave comments, you need to log in
How to add disabled to CharField values?
The Membership model has a role field of type CharField . Based on this model, the form ProjectMembersForm (ModelForm) was created. I'm trying to make the choice of some values () in choices inaccessible for the user in the form, so that he can see this value. For example: the value of developer is disabled. To do this, I decided to change the widget a little, but in the end, the value can still be selected. The template outputs:
<option value="{'disabled': True, 'label': 'developer'}">Developer</option>
ROLE_CHOICES = (
('manager', 'Manager'),
('developer', 'Developer'),
('singer', 'Singer'),
('musician', 'Musician'),
)
class Membership (models.Model):
***ДРУГИЕ ПОЛЯ***
role = models.CharField(max_length=20, choices=ROLE_CHOICES,)
class ProjectMembersForm(forms.ModelForm):
class Meta:
model = Membership
widgets = {
'role': SelectWithDisabled(),
}
exclude = ('project',)
def __init__(self, *args, **kwargs):
super(ProjectMembersForm, self).__init__(*args, **kwargs)
self.fields['role'].choices = tuple(choice if choice[0] not in ['developer'] else ({'disabled': True, "label": choice[0]}, 'Developer') for choice in ROLE_CHOICES)
class SelectWithDisabled(Select):
def render_option(self, selected_choices, option_value, option_label):
option_value = force_text(option_value)
if option_value in selected_choices:
selected_html = u' selected="selected"'
else:
selected_html = ''
disabled_html = ''
if isinstance(option_label, dict):
if dict.get(option_label, 'disabled'):
disabled_html = u' disabled="disabled"'
option_label = option_label['label']
return u'<option value="%s"%s%s>%s</option>' % (
escape(option_value), selected_html, disabled_html,
conditional_escape(force_text(option_label)))
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