我有一个表格,旨在为项目添加多个部分。我正在使用 CheckboxSelectMultiple ,其中的选项列表仅限于以前未选择的选项。
因此,对于没有部分的新空项目:
Project.sections.all() = null
选择 = [(1, 'a'),(2, 'b'),(3, 'c')]
第一次提交表单时,添加部分 a 和 b。
Project.sections.all() = a, b
选择 = [(3, 'c')]
第二次提交表单,添加部分 c。Project.sections.all() = c
选择 = [(1, 'a'),(2, 'b')]
相反,我想要的是将 c 添加到项目的现有值列表中。
模型.py
class Project(models.Model):
number = models.CharField(max_length=4, unique=True)
name = models.CharField(max_length=100)
sections = models.ManyToManyField(Section)
class Section(models.Model):
code = models.CharField(max_length=2)
description = models.CharField(max_length=50)
视图.py
def add_section(request, project_number):
project = Project.objects.get(number=project_number)
full_section_list = Section.objects.all()
project_assigned_sections = project.sections.all().values_list('id', flat=True)
choices = list(full_section_list.exclude(pk__in=project_assigned_sections).values_list('id', 'code'))
if request.method == 'POST':
form = AddSectionForm(choices, request.POST, instance=project)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse("project-page", args=(project_number)))
else:
print("invalid")
else:
form = AddSectionForm(choices, instance=project)
return render(request, "app/add_section.html", {
"project": project,
"form": form,
"choices": choices
})
表格.py
class AddSectionForm(forms.ModelForm):
def __init__(self, choices, *args, **kwargs):
super(AddSectionForm, self).__init__(*args, **kwargs)
self.fields['sections'] = forms.MultipleChoiceField(
widget=forms.CheckboxSelectMultiple,
required=False,
choices=choices
)
class Meta:
model = Project
fields = ['sections']