我用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)