在Django ModelForm

时间:2018-11-22 10:45:51

标签: python django django-models django-forms modelform

我的模特

class MyModel(models.Model):
    remark = models.CharField(max_length=120)
    data_1 = models.BooleanField(default=False)
    data_2 = models.BooleanField(default=False)
    data_3 = models.BooleanField(default=False)
    data_4 = models.BooleanField(default=False)

表格

class MyModelForm(forms.ModelForm):
    CHOICES= (("data_1", "data_1"),
               ("data_2", "data_2"),
               ("data_3", "data_3"),
               ("data_4", "data_4"),)
    my_choice = forms.MultipleChoiceField(choices=CHOICES, widget=forms.CheckboxSelectMultiple())
    class Meta:
        model = MyModel
        fields = ["remark"]

视图

class MyView(UpdateView):
    model = MyModel
    form_class = MyModelForm
    template_name = "mytemplate.html"

    def form_valid(self, form):
        selected_choices = self.request.POST.getlist("my_choice")
        for item in selected_choices:
            form.instance.item = False
        form.instance.remarks = form.cleaned_data["remark"]
        form.instance.save()
        return super(MyView, self).form_valid(form)

我想要的是,我要选择选定的选项,并通过选中复选框将其值更改为False,其余的必须不受影响。请帮助。...

1 个答案:

答案 0 :(得分:3)

这个问题很难理解,似乎与在表单中添加字段无关。但是我认为您正在寻找setattr

    for item in selected_choices:
        setattr(form.instance, item, False)