0

我已经在 stackoverflow 和 Internet 上查看过这个问题,所以我将只展示我的代码。

视图.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 模板没有显示错误。谢谢

4

1 回答 1

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)
于 2013-02-02T19:54:09.657 回答