2013-02-04 54 views
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)) 

我在做什麼錯?

回答

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)) 
相關問題