0

为什么我的代码不显示验证表单错误消息?我尝试这样的事情:

def index(request):
    if request.method == "POST":
        if request.POST['form-type'] == 'contact-form':
            form = AngebotForm(None, request.POST)
            if form.is_valid():
                form.save()
                msg = 'Good!'

                return render_to_response('index.html',{'msg':msg}, context_instance=RequestContext(request))

            else:
                form = AngebotForm()
        else:
            form = MessageForm(request.POST)
            if form.is_valid():
                form.save()
                msg = 'Good!'

                return render_to_response('index.html',{'msg':msg},context_instance=RequestContext(request))

            else:
                form = MessageForm()
    return render_to_response('index.html',{'a_form':AngebotForm(), 'm_form':MessageForm()},context_instance=RequestContext(request))

我究竟做错了什么?

4

1 回答 1

1

因为else部分原因是您正在重新初始化表单,这将失去当前的表单状态。

只需删除这些行:

else:
    form = MessageForm()

最后,您的视图应如下所示:

def index(request):
    form = AngebotForm()
    m_form = MessageForm()
    if request.method == "POST":
        if request.POST['form-type'] == 'contact-form':
            form = AngebotForm(None, request.POST)
            if form.is_valid():
                form.save()
                msg = 'Good!'

                return render_to_response('index.html',{'msg':msg}, context_instance=RequestContext(request))
        else:
            m_form = MessageForm(request.POST)
            if m_form.is_valid():
                m_form.save()
                msg = 'Good!'

                return render_to_response('index.html',{'msg':msg},context_instance=RequestContext(request))

    return render_to_response('index.html',{'a_form':form, 'm_form':m_form},context_instance=RequestContext(request))
于 2013-02-04T11:02:27.910 回答