我有一个models.py:
class MyModel(models.Model):
...
fries_with_that = models.BooleanField()
forms.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
。这是为什么?
非常感谢任何帮助。
修改:
views.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()
答案 0 :(得分:3)
试试这个:
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()