2013-02-02 82 views
0

我已经查看了所有关于此的stackoverflow和互联网,所以我只会显示我的代码。Django表单错误没有显示

views.py

def UserSell(request,username): 

theuser=User.objects.get(username=username) 
thegigform=GigForm() 
#if the user is submitting a form 
if request.method=='POST': 
    #bind form with form inputs and image 
    gigform=GigForm(request.POST,request.FILES) 
    if gigform.is_valid(): 
     gigform.title=gigform.cleaned_data['title'] 
     gigform.description=gigform.cleaned_data['description'] 
     gigform.more_info=gigform.cleaned_data['more_info'] 
     gigform.time_for_completion=gigform.cleaned_data['time_for_completion'] 
     gigform.gig_image=gigform.cleaned_data['gig_image'] 
     finalgigform=gigform.save(commit=False) 
     finalgigform.from_user=theuser 
     finalgigform.save() 
     return HttpResponseRedirect('done') 
thegigform=GigForm() 
context=RequestContext(request) 
return render_to_response('sell.html',{'theuser':theuser,'thegigform':thegigform},context_instance=context) 

模板

<form action="{% url sell user.username %}" method="post" enctype="multipart/form-data"> 
{% csrf_token %} 
<fieldset> 
    <legend><h2>Sell A Gig</h2></legend> 
    {% for f in thegigform %} 
    <div class="formWrapper"> 
     {{f.errors}} 
     {{f.label_tag}}: {{f}} 
     {{f.help_text}} 
    </div> 
    {% endfor %} 
</fieldset> 
<input type="submit" value="Sell Now!" /> 

此代码似乎遵循普通的Django形式的协议,请告诉我为什么我的Django的模板犯规显示错误。谢谢

回答

3

它看起来像你缺少一个else块。

如果gigform.valid()返回false,则覆盖变量“thegigform”。尝试重新构造你的代码,如下所示:

if request.method=='POST': 
    #bind form with form inputs and image 
    thegigform=GigForm(request.POST,request.FILES) 
    if thegigform.is_valid(): 
     thegigform.title=gigform.cleaned_data['title'] 
     thegigform.description=gigform.cleaned_data['description'] 
     thegigform.more_info=gigform.cleaned_data['more_info'] 
     thegigform.time_for_completion=gigform.cleaned_data['time_for_completion'] 
     thegigform.gig_image=gigform.cleaned_data['gig_image'] 
     finalgigform=gigform.save(commit=False) 
     finalgigform.from_user=theuser 
     finalgigform.save() 
     return HttpResponseRedirect('done') 
else: 
    thegigform=GigForm() 
context=RequestContext(request) 
return render_to_response('sell.html',{'theuser':theuser,'thegigform':thegigform},context_instance=context) 
+0

这就是我在我的代码之前,但被告知要改变,所以我把其他回来赶上,如果请求得到。问题没有解决 –

+0

你看到为什么在你的发布代码中你永远不会看到错误?如果gigform.is_valid()返回False,那么你就像request.method!='POST'一样沿着相同的代码路径。也就是说,您正在创建一个新的GigForm对象。要查看呈现的错误,您需要在上下文中将'thegigform'设置为导致gigform.is_valid()返回False的相同对象。 –

+0

所以上下文将gigform?我很抱歉,如果遇到问题,可以告诉我代码应该是什么样子。 thegigform = gigform .... {'thegigform':thegigform}像那样? –