Python Django-使窗体记住其复选框值
我将使用基本设置解决此问题:Python Django-使窗体记住其复选框值,python,django,forms,validation,checkbox,Python,Django,Forms,Validation,Checkbox,我将使用基本设置解决此问题: # 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") #
# 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'
现在假设我选中复选框并只填写一个必填字段。表单显然没有通过验证,返回时出现了错误。问题是,复选框的值返回时未选中。这对于一个布尔域来说并不是什么大问题,但我正在从事一个项目,在这个项目中我有很多复选框。从头开始检查它们是相当令人沮丧的。
因此,我查阅了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
但它不起作用。同样,在表单未通过验证后,复选框会失去状态,所以我想这不是我想要的
所以我的问题是,有没有办法做到这一点?我很确定应该有一个,如果你们中的一些人至少能把我带向正确的方向,那就太好了。谢谢:-)
编辑
经过一点调试,我解决了这个问题。原来我使用了一个自定义模板来创建crispy forms复选框,我在其中发现了一个小错误。您的视图需要从
请求中填充表单。按此方式发布字典:
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})
除非传递请求.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})
也许问题在你看来:
查看示例:
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})
你可以发布视图?当然可以,但我认为这一点都没有帮助。它只是一个基本的FormView子类,没有什么特别之处。无论如何,我添加它只是为了进一步了解。问题是我发布了一个示例的视图。您如何在模板中显示字段?我使用django crispy表单进行渲染,这应该没问题。我基本上让表单自己打印,而不需要任何花哨的定制。我仍在调查原因,但现在我并不认为这与Django有关。我使用的是基于类的视图,因此表单应该在POST方法中自动填充request.POST数据。顺便说一句,CharField返回了我发布的值,只是复选框没有选中。也许我应该更好地解释我自己。但无论如何,谢谢你的回答。你可以查看我在@Brandon上发布的答案,应该也适用于你的回复。不过还是要谢谢你的关注。