Django 表单 is_valid() 失败 [英] Django form is_valid() fails
问题描述
我是网络开发的真正初学者.以下代码在 is_valid()
检查中失败.但我不明白为什么:表单是否应该从 POST 数据中获取其数据?
I am a real beginner in web development. The following code is failing at the is_valid()
check. But I do not understand why: The form should get its data filled from the POST-data or not?
型号:
class Statement(models.Model):
text = models.CharField(max_length=255)
user = models.ForeignKey(User)
time = models.DateField()
views = models.IntegerField()
模型形式:
class StatementForm(ModelForm):
class Meta:
model = Statement
widgets = {
'time':forms.HiddenInput(),
'user':forms.HiddenInput(),
'views':forms.HiddenInput(),
}
查看功能:
def new(request):
if request.method == 'POST': # If the form has been submitted...
form = StatementForm(request.POST) # A form bound to the POST data
if form.is_valid():
stmt = form.save()
path = 'stmt/' + stmt.id
return render_to_response(path, {'stmt': stmt})
else:
c = {}
c.update(csrf(request))
loggedin_user = request.user
d = datetime.now()
form = StatementForm(request.POST, initial={'time': d.strftime("%Y-%m-%d %H:%M:%S"), 'user':loggedin_user, 'views':0})
return render_to_response('new_stmt.html', {'form': form, },context_instance=RequestContext(request))
我找到了类似的主题并尝试了很多.这就是我认为它应该工作的方式.我真的需要建议.
I found similar topics and tried a lot. This is how i think it should work. I really need advice.
推荐答案
您的模型的所有字段都是必需的.因此,form.is_valid()
将是 True,如果所有字段都填充了正确的值并且没有空白.您已将字段 time
、user
、views
声明为隐藏字段.您确定已将它们填写在模板表单中吗?此外,您可能希望自动标记字段 time = models.DateField()
.修改您的模型字段,如
All fields of your model are required. So, form.is_valid()
will be True, if all fields are filled with correct values and are not blanked.
You have declared fields time
, user
, views
as hidden fields. Are you sure, that you have filled them in your template form?
Also, you may want to auto stamp field time = models.DateField()
. Modify your model field like
time = models.DateField(auto_now=True)`.
此后您就不必在模板表单中自己填写了.
After this you don't have to fill it by yourself in template form.
您的视图在所有情况下都必须返回 HttpResponse 对象.如果您的表单无效,即如果 form.is_valid()
将返回 False,那么您的视图将不会返回 HttpResponse
对象.这可能是你失败的根源.为if form.is_valid()
添加else
语句:
Your view must return HttpResponse object in all cases. If your form is not valid, i.e. if form.is_valid()
will return False, then no HttpResponse
object will be returned by your view. This can be the source of your fail. Add else
statement for if form.is_valid()
:
from django.http import Http404
def new(request):
if request.method == 'POST': # If the form has been submitted...
form = StatementForm(request.POST) # A form bound to the POST data
if form.is_valid():
stmt = form.save()
path = 'stmt/' + stmt.id
return render_to_response(path, {'stmt': stmt})
else:
# Do something in case if form is not valid
raise Http404
else:
# Your code without changes
这篇关于Django 表单 is_valid() 失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!