2

我有一个models.py:

class MyModel(models.Model):
    ...
    fries_with_that = models.BooleanField()

表格.py:

class MyModelForm(ModelForm):

    class Meta:
        model = MyModel
        fields = (
            'fries_with_that',
        )

这很好用,并为我提供了“未知”、“是”和“否”作为选择的下拉菜单。但我真的想要一个复选框。所以我补充说:

编辑

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

            self.fields['fries_with_that'].widget = forms.CheckboxInput()

现在我得到一个复选框,但是当被选中时,表单返回一个值None。为什么是这样?

编辑

视图.py:

form = MyModelForm(request.POST or None)
if form.is_valid():
    # UPDATE PROJECT
    updated = MyModel.objects.filter(
        project_id=project_id
    ).update(**form.cleaned_data)
    if updated == 0:
        project = form.save()
4

1 回答 1

5

尝试这个:

class MyModelForm(ModelForm):

    fries_with_that = forms.BooleanField(widget=forms.CheckboxInput, default=False)

    class Meta:
        model = MyModel
        fields = (
            'fries_with_that',
        )

实际上,这应该呈现复选框。

fries_with_that = forms.BooleanField() 
于 2013-06-07T20:03:20.317 回答