gpt4 book ai didi

python - 如何禁用 MultipleChoiceField 中的复选框?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:57:16 24 4
gpt4 key购买 nike

我在表单中使用 MultipleChoiceField。它向我显示了带有复选框的 REQUIREMENTS_CHOICES 列表,用户可以在其中选择新需求并将其添加到数据库中。是否可以禁用数据库中已有的复选框(在我的情况下是要求)?假设我在数据库中有 A 和 C,所以我不需要它们。

tulpe中第一个值是需求符号,第二个值是需求名称。

模型.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)

表单.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)

最佳答案

您可以在表单初始化时对其进行操作:

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 选项。

关于python - 如何禁用 MultipleChoiceField 中的复选框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43611282/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com