0

my model

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)

Form

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"]

view

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)

what i want is, i want to take the selected choices and change its value to False by checking the checkbox and remaining must be unaffected.Please help....

1
  • sorry for that :) Commented Nov 22, 2018 at 10:51

1 Answer 1

3

This question is hard to understand and doesn't seem to have anything to do with adding fields to forms. But I think you are looking for setattr:

    for item in selected_choices:
        setattr(form.instance, item, False)
Sign up to request clarification or add additional context in comments.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.