pythonhmmm
pythonhmmm

Reputation: 923

Multiple checkbox in django form

class Test(models.Model):
    name = models.CharField(max_length=60)
    address = models.CharField(max_length ==200)    

class TestForm(ModelForm):
    class Meta:
        model = Test

and in my view I use:

frm= TestForm(request.POST,instance=test)
if frm.is_valid():
    frm.save()

I need to add multiple checkbox values in my model.

APPROVAL_CHOICES = (
    ('yes', 'Yes'),
    ('no', 'No'),
    ('cancelled', 'Cancelled'),
)

checkbox_value = models.CharField(max_length = 250)

I am not using checkbox_value = models.CharField(choices=APPROVAL_CHOICES) in my model as depending upon some condition my Approval_choice tuple my change.

So how can I use checkbox in my model form? Will it be helpful if I create a custom form?

Thanks.

Upvotes: 2

Views: 2654

Answers (1)

Reinbach
Reinbach

Reputation: 771

You can add the checkbox_value to your model, without any specified choices. But instead have the APPROVAL_CHOICES determined in the form;

APPROVAL_CHOICES = (
    ('yes', 'Yes'),
    ('no', 'No'),
    ('cancelled', 'Cancelled'),
)

class Test(models.Model):
    name = models.CharField(max_length=60)
    address = models.CharField(max_length=200)
    checkbox_value = models.CharField(max_length=250)

class TestForm(ModelForm):
    checkbox_value = forms.ChoiceField()

    class Meta:
        model = Test

    def __init__(self, *args, **kwargs):
        super(TestForm, self).__init__(*args, **kwargs)

        # add your relevant conditions that determines the approval choice
        # if you want to be able to modift the APPROVAL_CHOICES, change it 
        # to a list rather than a tuple
        # else
        approval_choices = APPROVAL_CHOICES

        self.fields['checkbox_value'].choices = approval_choices

Upvotes: 3

Related Questions