0

我有一个表格,旨在为项目添加多个部分。我正在使用 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']
4

3 回答 3

0

我假设 Django 正在做它打算做的事情......所以,解决它。

if request.method == 'POST':
    previous_sections = list( project.sections.values_list( 'pk', flat=True) )
    form = AddSectionForm(choices, request.POST, instance=project)
    if form.is_valid():
        new = form.save( commit = False)
        new.sections.add( previous_sections ) # make sure old ones are never removed
        new.save()
        return HttpResponseRedirect(reverse("project-page", args=(project_number)))
    else:
        print("invalid")
于 2022-02-18T11:24:30.150 回答
0
else:   
    form = AddSectionForm()

不要传递实例只是保持它为空

于 2022-02-18T11:27:42.963 回答
0

好的,这可行并且看起来更好(我不再将整数映射到返回的列表)。

            data = form.cleaned_data.get("sections") #get the list of id's from the form
            sections = Section.objects.filter(pk__in=data) #gets the objects from those id's
            for section in sections:  #iterate through them, adding to the project.
               project.sections.add(section)
于 2022-02-18T15:58:42.853 回答