我正在尝试做一些我认为很常见的事情,但我真的不确定如何实现它。
我有模态'要求'。每个要求都有自己的名称和唯一代码。我希望使用REQUIREMENTS_CHOICES list
显示带有复选框的表单。用户可以选择他们需要的复选框。如何在Django中制作它?
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:
class RequirementAddForm(forms.ModelForm):
name = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple, choices=REQUIREMENTS_CHOICES,)
class Meta:
model = Requirement
fields = ('symbol',)
REQUIREMENTS_CHOICES = (
('A', 'Name A'),
('B', 'Name B'),
('C', 'Name C'),
)
views.py:
def requirement_add(request, project_code):
data = dict()
if request.method == 'POST':
form = RequirementAddForm(request.POST)
if form.is_valid():
symbols = form.cleaned_data.get('symbol') # List of symbols which user selected ['A', 'C']
for symbol in symbols:
requirement = form.save(commit=False)
requirement.symbol = symbol
requirement.name = symbol.get_symbol_display() #???
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 = GroupRequirementAddForm()
context = {'form': form}
data['html_requirement_form'] = render_to_string('project/requirement_add.html', context, request=request)
return JsonResponse(data)