如何在MultipleChoiceField禁用复选框?(How to disable checkb

2019-09-27 17:40发布

我用MultipleChoiceField形式。 它显示我REQUIREMENTS_CHOICES与复选框,其中用户可以选择和添加新的要求数据库列表。 是否有可能禁用复选框(在我的情况的要求),这是已经在数据库中? 可以说我有A和C在数据库中,因此我不需要他们。

在tulpe第一值的要求的符号,第二值是需要的名字。

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)

forms.py:

REQUIREMENTS_CHOICES = (
        ('A', 'Name A'),
        ('B', 'Name B'),
        ('C', 'Name C'),
        ('D', 'Name D'),
)


class RequirementAddForm(forms.ModelForm):
    symbol = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple, choices=REQUIREMENTS_CHOICES,)

    class Meta:
        model = Requirement
        fields = ('symbol',)

views.py:

def requirement_add(request):
    data = dict()
    if request.method == 'POST':
        form = RequirementAddForm(request.POST)
        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()
            data['form_is_valid'] = True
            requirements = Requirement.objects.filter()
            context = {requirement': requirement, 'requirements': requirements}
            data['html_requirement'] = render_to_string('project/requirement_list.html', context)
        else:
            data['form_is_valid'] = False
    else:
        form = RequirementAddForm()
    context = {'form': form}
    data['html_requirement_form'] = render_to_string('project/requirement_add.html', context, request=request)
    return JsonResponse(data)

Answer 1:

你可以操纵你的形式在它的初始化:

REQUIREMENTS_CHOICES = (
        ('A', 'Name A'),
        ('B', 'Name B'),
        ('C', 'Name C'),
        ('D', 'Name D'),
)


class RequirementAddForm(forms.ModelForm):
    def __init__(self, symbols='', *args, **kwargs):
        super(RequirementAddForm, self).__init__(*args, **kwargs)

        UPDATED_CHOICES = () # empty tuple
        for choice in REQUIREMENTS_CHOICES:
            if choice[1] not in symbols:
                UPDATED_CHOICES += (choice,) # adds choice as a tuple

        self.fields['symbol'] = forms.MultipleChoiceField(
                                    required=False,
                                    widget=forms.CheckboxSelectMultiple, 
                                    choices=UPDATED_CHOICES,
                                )

    class Meta:
        model = Requirement

以上会发生什么:

  1. 当你初始化形式
    (例如: form=RequirementAddForm(symbols=existing_symbols)可以传递给构造函数,与现有的符号的字符串为您的数据库中的一个项目。
  2. __init__功能检查,这在已经存在的选择symbols ,并更新UPDATED_CHOICES相应。
  3. 字段命名symbol被添加到从构造形式,其具有作为选择的UPDATED_CHOICES


文章来源: How to disable checkboxes in MultipleChoiceField?