分配前引用的局部变量 [英] Local Variable referenced before assignment

查看:39
本文介绍了分配前引用的局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道你们是否可以提供帮助.我正在尝试做一个简单的视图,它将用户发送到客户端创建表单,但我不断收到此错误:

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:

赋值前引用的局部变量'form'

local variable 'form' referenced before assignment

看看我的代码,我看不出有什么问题.

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?

推荐答案

这是正在发生的事情:

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

至于如何修复它,这真的由您来决定.如果请求方法不是 POST,修复方法取决于您希望代码做什么.

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.

这篇关于分配前引用的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆