【发布时间】:2013-12-24 06:06:57
【问题描述】:
我正在使用 Django 表单,但由于某种原因,此表单无法验证!它可以提交,或者至少运行服务器显示带有代码 200(ok)的 http post 响应。但由于某种原因,我的表单无法通过 is_valid 测试!
views.py:
def new_show(request):
if request.method == 'POST':
img_form = ImageForm(request.POST, request.FILES)
show_form = NewShowForm(request.POST)
if show_form.is_valid():
new_Show = Show()
new_Show.title=show_form.cleaned_data['title']
new_Show.body=show_form.cleaned_data['body']
new_Show.pub_date=timezone.now()
new_Show.location=show_form.cleaned_data['location']
new_Show.time=show_form.cleaned_data['time']
new_Show.save()
if img_form.is_valid():
image=Image(image=request.FILES['imageFile'])
new_Show.image_set.add(image)
return HttpResponseRedirect(reverse('shows'))
else:
return HttpResponseRedirect(reverse('shows'))
else:
show_form = NewShowForm()
img_form = ImageForm()
return render_to_response(
'shows/new_show.html',
{'show_form': show_form, 'img_form': img_form},
context_instance=RequestContext(request)
)
这是我的模板 sn-p:
<form action="{% url "new_show" %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ show_form.non_field_errors }}</p>
<p>
<label for="title">Title:</label>
<input type="text" name="title"/>
</p>
<p>
<label for="body">Body:</label>
<textarea type="text" name="body"> </textarea>
</p>
<p>
<label for="location">Location:</label>
<input type="text" name="location"/>
</p>
<p>
<label for="time">Date:</label>
<input type="text" id="time" maxlength="25" size="25" name="time"><a href="javascript:NewCal('time','ddmmmyyyy',true,24)"><img src="{{ STATIC_URL }}../../static/cal.gif" width="16" height="16" border="0" alt="Pick a date"></a>
</p>
<!-- Upload Form. Note enctype attribute! -->
{% csrf_token %}
<p>{{ img_form.non_field_errors }}</p>
<p>{{ img_form.imageFile.label_tag }}</p>
<p>
{{ img_form.imageFile.errors }}
{{ img_form.imageFile }}
</p>
<p><input type="submit" value="Add Upcoming Show"></input></p>
</form>
这是我的表单类:
class NewShowForm(forms.Form):
title=forms.CharField()
body=forms.CharField(widget=forms.TextArea)
location=forms.CharField()
time=forms.DateTimeField(required=True)
class ImageForm(forms.Form):
imageFile = forms.FileField(required=False, label='Select an Image')
请帮帮我!
【问题讨论】:
-
请 a) 尝试修正缩进 b) 显示表单类声明。
-
好的,我想我的缩进是对的。我添加了 forms.py
-
基于对表单代码的快速浏览,我突然想到了两件事。一,默认情况下需要字段-您为
time指定了required=True,但这不是必需的。如果您提交时未设置title、body或location的值,则该表单无效。如果这不是问题,我会检查为您的time输入传递了哪些值。您已将其声明为DateTimeField,并且如果您的 Javascript 小部件未生成该字段可以解析的字符串,则该字段无效。提交后您是否看到表单错误消息? -
不,我没有看到任何错误,即使我提交时没有输入任何值,这很奇怪。我认为你是对的,我取出了 javascript 小部件,它似乎正在工作......我将继续处理日期时间字段的格式
-
这并不奇怪 - 除了
non_field_errors,您的模板不会呈现来自show_form的错误。如果你想自己渲染每个字段,你应该在某处渲染每个字段的errors属性。
标签: python html django forms validation