我正在尝试声明一个表单集:

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”。我不知道这是什么问题,有人可以帮我吗?谢谢 !

最佳答案

缩进的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()

关于python - Django 1.6 Formset的错误:“分配前已被引用”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22337057/

10-16 09:31