分配错误之前引用了局部变量“实例”

时间:2018-06-21 01:16:02

标签: django python-2.7

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

错误: 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在执行任何操作之前已初始化。

1 个答案:

答案 0 :(得分:0)

此行出现错误

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

被执行。该代码未完全生效。因此,该实例尚未确定。然后代码转到

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

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

The error:  Local variable 'instance' referenced before assignment

发生。