我将使用基本设置解决此问题:
# models.py
class MyModel(models.Model):
required_field = models.CharField("some label", max_length=10)
another_required_field = models.CharField("some label", max_length=10)
checkbox = models.BooleanField("some label")
# forms.py
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
# views.py
class MyView(FormView):
form_class = MyForm
template_name = 'some-template.html'
现在假设我选中了复选框并只填写其中一个必填字段。表单显然没有通过验证,并且错误地返回所有内容。问题是,复选框的值未经检查。这对于一个BooleanField来说并不是什么大问题,但是我正在开展一个项目,我有很多复选框。从头开始检查它们是相当令人沮丧的。 所以我检查了django的文档,并偶然发现了有关BooleanFields的这一段:
Since all Field subclasses have required=True by default, the validation condition here
is important. If you want to include a boolean in your form that can be either True or
False (e.g. a checked or unchecked checkbox), you must remember to pass in
required=False when creating the BooleanField.
我这样做了:
# forms.py
class MyForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
for field in self.fields:
if isinstance(field, forms.CheckboxInput):
self.fields[field].required = False
class Meta:
model = MyModel
但它没有用。同样,复选框在表单未通过验证后失去状态,所以我想这不是我想要的。
所以我的问题是,有没有办法实现这一目标?我非常确定应该有一个,如果你们中的一些人能够至少让我朝着正确的方向前进,那就太棒了。谢谢: - )
修改 经过一些调试,我解决了这个问题。事实证明我使用自定义模板进行脆形表复选框,我发现了一个小错误。
答案 0 :(得分:0)
您的视图需要填充request.POST
字典中的表单:
def your_view(request):
form = MyForm(request.POST or None)
if request.method == 'POST' and form.is_valid():
form.save()
# do whatever esle
return render(request, 'your-template.html', {'form': form})
除非您传递request.POST
数据和/或您正在编辑的模型实例,否则您的表单将不受约束,因此不会显示POST数据中存在的任何值或来自你的模特。如果您正在编辑实例,它将如下所示:
def your_view(request, id):
my_model_instance = MyModel.objects.get(pk=id)
form = MyForm(request.POST or None, instance=my_model_instance)
if request.method == 'POST' and form.is_valid():
form.save()
# do whatever esle
return render(request, 'your-template.html', {'form': form})
答案 1 :(得分:0)
也许你的观点存在问题:
查看示例:
def view(request):
if request.method == 'POST':#bound the form wit data from request.Post
form = MyForm(request.POST)
if form.is_valid():
#do somthing
form.save()
#if form not valid render the page.html with form that has request.Post data
return render(request,'some-template.html',{'form': form})
else:
form = MyForm()
return render(request, 'some-template.html',{'form': form})