2
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元组我的变化。

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

谢谢。

4

1 回答 1

3

您可以将 checkbox_value 添加到您的模型中,而无需任何指定的选择。但取而代之的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
于 2012-09-22T13:56:00.147 回答