Django 1.6 Formset的错误:“在分配之前引用”

时间:2014-03-11 21:30:36

标签: python django

我正在尝试声明一个formset:

def linkurl(request):
  UrlFormSet = formset_factory(UrlForm)
  if request.method == 'POST':
    formset = UrlFormSet(data=request.POST, instance=Link())
    if formset.is_valid():
      formset.instance.user = request.user
      formset.save()
      return redirect('home')
    else:
      formset = UrlFormSet()
  user_links_count = Link.objects.filter(user=request.user).count()
  return render_to_response(request, "addurl.html", {'formset': formset, 'linkscount': user_links_count})

但它总是打印我:在赋值之前引用的局部变量'formset'。我不知道是什么问题,有人可以帮帮我吗?谢谢!

1 个答案:

答案 0 :(得分:4)

你有错误的缩进else块,向左移动一步:

if request.method == 'POST':
    formset = UrlFormSet(data=request.POST, instance=Link())
    # code
else: # this else block in your code should be moved left
    formset = UrlFormSet()