13

我是 Web 开发的真正初学者。以下代码在is_valid()检查时失败。但我不明白为什么:表单是否应该从 POST 数据中获取数据?

模型:

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))

我找到了类似的主题并尝试了很多。这就是我认为它应该工作的方式。我真的需要建议。

4

2 回答 2

14

模型的所有字段都是必需的。因此,form.is_valid()如果所有字段都填充了正确的值并且没有空白,则为 True。您已将 fields timeuser、声明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
于 2012-06-17T14:36:53.067 回答
3

更改此行:

    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})
于 2012-06-17T14:31:16.520 回答