简体   繁体   English

分配前引用的局部变量

[英]Local Variable referenced before assignment

I was wondering if you guys could help. 我想知道你们是否可以提供帮助。 I'm trying to do a simple view where it sends the user to the client creation form, but I keep getting this error: 我正在尝试做一个简单的视图,它将用户发送到客户端创建表单,但是我一直收到此错误:

local variable 'form' referenced before assignment 赋值之前引用的局部变量“ form”

Looking at my code, I can't see whats wrong. 查看我的代码,看不到有什么问题。

def add_client(request):
    user = request.user
    if request.method =='POST':
        form = AddClientForm(request.POST)
        if form.is_valid():
            client = form.save(commit=False)
            client.save()
            return HttpResponseRedirect('/')
        else:
            form = AddClientForm()

    return render_to_response('clients/addClient.html', { 'form': form, 'user': user, }, context_instance=RequestContext(request))

Anyone tell me where I went wrong? 有人告诉我我哪里出问题了吗?

This is what is happening: 这是正在发生的事情:

  1. The if block is not being entered. 没有输入if块。
  2. The form variable is not defined. 未定义form变量。
  3. You then attempt to refer to the form variable in the return statement. 然后,您尝试在return语句中引用form变量。

As to how to fix it, that's really for you to decide. 至于解决方法,这确实是您要决定的。 What the fix is depends on what you want your code to do in case the request method is not POST . 解决的方法取决于在请求方法不是POST情况下您希望代码执行的操作。

You almost certainly want to de-indent this part: 您几乎可以肯定要缩进这部分:

else:
    form = AddClientForm()

That is, on the initial GET of the page, use a blank client form, then when the page is POSTed, use the request POST data to fill in the form object. 也就是说,在页面的初始GET上,使用空白客户端表单,然后在对页面进行POST时,使用请求POST数据填写表单对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM