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

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

问题描述

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


本地


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

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

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

发生错误?



谢谢

解决方案


  1. 如果块没有输入,

  2. 未定义表单变量

  3. 然后尝试参考表单 $ <$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b

    至于如何解决这个问题,那真的是你决定的。如果请求方法不是 POST ,那么修复程序取决于您希望代码执行的操作。


    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

    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?

    Thanks

    解决方案

    This is what is happening:

    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.

    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天全站免登陆