我正在处理表单验证。由于某种神秘的原因,我的form.is_valid()
返回false。我在这里查看了其他相关主题,但没有一个有帮助。我没有从form.errors
得到任何错误。
视图:
def index(request):
form = TestCaseForm()
if request.method == 'POST':
if form.is_valid():
TestCase.objects.create(
name=request.POST['name'],
documentation=request.POST['documentation'],
steps=request.POST['steps'],
tags=request.POST['tags'],
setup=request.POST['setup'],
teardown=request.POST['teardown'],
template=request.POST['template'],
timeout=request.POST.get(int('timeout')),
)
return redirect('/list')
else:
for i in form.errors:
print(i)
return render(request, 'index.html', {'form': form})
forms.py:
class TestCaseForm(forms.Form):
name = forms.CharField(widget=forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'Enter Name'}), label='')
documentation = forms.CharField(widget=forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'Enter Documentation'}), label='')
steps = forms.CharField(widget=forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'Enter Steps'}), label='')
tags = forms.CharField(widget=forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'Enter Tags'}), label='')
setup = forms.CharField(widget=forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'Enter Setup'}), label='')
teardown = forms.CharField(widget=forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'Enter Teardown'}), label='')
template = forms.CharField(widget=forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'Enter Template'}), label='')
timeout = forms.CharField(widget=forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'Enter Timeout (optional)'}),
required=False, label='')
models.py:
class TestCase(models.Model):
"""
The test case
"""
name = models.CharField(max_length=200)
documentation = models.CharField(max_length=2048, blank=True)
steps = models.CharField(max_length=2048, blank=True)
tags = models.CharField(max_length=200, blank=True)
setup = models.CharField(max_length=2048, blank=True)
teardown = models.CharField(max_length=2048, blank=True)
template = models.CharField(max_length=200, blank=True)
timeout = models.IntegerField(default=10)
def __str__(self):
return self.name
html:
<form method="POST" action="/">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" class="btn btn-primary" name="submit" value="Submit"
style="margin-top:10px;" />
答案 0 :(得分:0)
form = TestCaseForm()
if request.method == 'POST':
if form.is_valid():
您尚未将表格绑定到任何数据。因此,form.is_valid()
将始终为False
,而form.errors
将为空。
更改视图以使用以下结构:
if request.method == 'POST':
# Bound form for POST requests
form = TestCaseForm(request.POST)
if form.is_valid():
...
else:
# Unbound form for GET request
form = TestCaseForm()