在赋值之前引用的局部变量'data'

时间:2017-07-07 14:50:07

标签: python django blogs

/ post /的UnboundLocalError 在赋值之前引用的局部变量'data' 请求方法: POST 请求网址: http://127.0.0.1:8000/post/ Django版本: 1.11.3 例外类型: UnboundLocalError 例外价值: 在赋值之前引用的局部变量'data' 例外地点: 索引中的D:\ website \ formapp \ views.py,第56行

def index(request):
if request.method == 'POST':
    form = Postform(request.POST,request.FILES)
    if form.is_valid():
        f=form.save(commit=False)
        f.user=request.user
        f.save()
        return HttpResponseRedirect('/post/')
else:
    form = Postform()
    data=Post.objects.order_by('-date_created')
return render(request,'home2.html',{'form':form,'data':data})
class Postform(forms.ModelForm):
pic=models.FileField()
vid=models.FileField()
class Meta:
    model=Post
    #fields=['title','content','pic'] 
    fields='__all__'
<form action=' ' method = 'POST' enctype="multipart/form-data">
{% csrf_token %}
<h3>Title:</h3> {{form.title}}<br><br>
<h3>Content:</h3> {{form.content}}<br><br>
<h3>Pic: </h3>{{form.pic}}<br>
<button type= 'submit' class='btn btn-primary btn-md'>Save</button>
<br><br>
</form>

1 个答案:

答案 0 :(得分:1)

如果form.is_valid()返回False,您必须为data分配一个值。

def index(request):

    if request.method == 'POST':
        form = Postform(request.POST,request.FILES)
        if form.is_valid():
            f=form.save(commit=False)
            f.user=request.user
            f.save()
            return HttpResponseRedirect('/post/')
    else:
        form = Postform()

    data=Post.objects.order_by('-date_created') # take this out of the `else` block.
    return render(request,'home2.html',{'form':form,'data':data})