我是网络开发的真正初学者。以下代码在is_valid()
检查时失败。但我不明白为什么:表单应该从POST数据中填充数据吗?
型号:
class Statement(models.Model):
text = models.CharField(max_length=255)
user = models.ForeignKey(User)
time = models.DateField()
views = models.IntegerField()
的ModelForm:
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))
我找到了类似的主题,并尝试了很多。这就是我认为应该如何运作的方式。我真的需要建议。
答案 0 :(得分:7)
您的模型的所有字段都是必需的。因此,如果所有字段都填充了正确的值且未被消隐,则form.is_valid()
将为True。
您已将字段time
,user
,views
声明为隐藏字段。你确定,你已经填写了模板表格吗?
此外,您可能希望自动标记字段time = models.DateField()
。修改您的模型字段,如
time = models.DateField(auto_now=True)`.
在此之后,您不必自己以模板形式填写它。
您的视图必须在所有情况下都返回HttpResponse对象。如果您的表单无效,即如果form.is_valid()
将返回False,那么您的视图将不会返回HttpResponse
个对象。这可能是您失败的根源。为else
添加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
答案 1 :(得分:2)
更改此行:
form = StatementForm(request.POST, initial={'time': d.strftime("%Y-%m-%d %H:%M:%S"), 'user':loggedin_user, 'views':0})
为此:
form = StatementForm(initial={'time': d.strftime("%Y-%m-%d %H:%M:%S"), 'user':loggedin_user, 'views':0})