【问题标题】:local variable 'instance' referenced before assignment error分配错误之前引用的局部变量“实例”
【发布时间】:2018-06-21 01:16:01
【问题描述】:

现在我已经阅读了关于这个错误的所有帖子,我可以得出结论,我的错误是完全不同的情况。

错误: Local variable 'instance' referenced before assignment [21/Jun/2018 09:05:58] "POST /details/create/ HTTP/1.1" 400 54

下面是我初始化instance的代码:

def create(request):
if request.method == "POST":
    try:
        params = post_data(request)

        try:
            instance = Sales_detail.objects.get(id = params.get("id",None))
            params["item"] = instance.item.pk
            params["price"] = instance.price.pk
            params["sales"] = instance.sales.pk
            detail_form = Detail_form(params, instance = instance)
        except Sales_detail.DoesNotExist:
            params["item"] = instance.item.pk
            params["price"] = instance.price.pk
            params["sales"] = instance.sales.pk
            detail_form = Detail_form(params)

        if detail_form.is_valid():
            detail_form.save()
        else:
            raise_error(detail_form.errors,True)

        return success("Details successfully saved.")
    except Exception as e:
        return error(e)
else:
    return redirect("dashboard")

我不知道我错过了什么,显然instance 在对其进行任何操作之前已被初始化。

【问题讨论】:

  • instance 未在异常处理程序中初始化。
  • 在try块之外引用实例,或者在捕获到异常时再次引用它
  • @StephenRauch 指出。我现在试试

标签: django python-2.7


【解决方案1】:

这一行出现错误

instance = Sales_detail.objects.get(id = params.get("id",None))

被执行。代码没有完全执行。所以这个例子还没有确定。然后代码转到

params["item"] = instance.item.pk

由于尚未确定instance,因此错误

The error:  Local variable 'instance' referenced before assignment

发生。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-07
    • 2018-07-16
    • 2014-08-20
    • 1970-01-01
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多