如何将django中的BooleanField设置为从模型中选取的值?

时间:2011-08-26 16:59:27

标签: django django-forms

我能够在模型中正确保存“私人”的值。但是,当我打开编辑页面时,无论值是True还是False,它总是设置为未选中。

# from forms.py
class MyEditForm(forms.Form)
    title = forms.CharField(
        label='Title',
        widget=forms.TextInput(attrs={'size': 64})
        )
    private = forms.BooleanField(
        label='Private',
        required=False,
    )

# from models.py
class MyData(models.Model):
    title = models.CharField(max_length=200)
    private = models.BooleanField()

# from views.py
def save_page(request)
    try:
        mydata = MyData.objects.get(
            private=private
        )
        title = mydata.title
        private = mydata.private
    except ObjectDoesNotExist:
        pass
    form = MyEditForm({
        'title': title,
        'private': private
    })

1 个答案:

答案 0 :(得分:1)

您应该使用ModelForm而不是Form。然后,当您实例化ModelForm时,将实例设置为您的模型。这也将使您无需复制表单字段,因为django将根据模型自动生成表单字段。

foo = Foo.objects.get(id=foobar)
form = YourForm(instance=foo)