django形式的多个复选框

时间:2012-09-22 06:54:24

标签: django django-models django-forms

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

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

在我看来我使用:

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

我需要在模型中添加多个复选框值。

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

checkbox_value = models.CharField(max_length = 250)

我没有在我的模型中使用checkbox_value = models.CharField(choices=APPROVAL_CHOICES),因为我的Approval_choice改变了某些条件。

那么如何在我的模型表单中使用复选框? 如果我创建自定义表单会有用吗?

感谢。

1 个答案:

答案 0 :(得分:3)

您可以将复选框值添加到模型中,而无需任何特定选择。但是要在表单中确定APPROVAL_CHOICES;

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