Django表单错误没有显示出来

时间:2013-02-02 19:42:46

标签: python django

我已经遍历了stackoverflow和互联网,所以我只会展示我的代码。

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模板不显示错误。感谢

1 个答案:

答案 0 :(得分:3)

看起来你错过了一个其他区块。

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