0

我的views.py是

def editbook(request,book_id):
    log.debug("test....")
    if request.POST:
        book_name =request.POST['book_name']
        publisher_name =request.POST['publisher_name']
    books=Book.objects.filter(book_id=book_id).update(book_name=book_name, publisher_name=publisher_name)
    first_name = request.POST('first_name')
        last_name = request.POST('last_name')
        email = request.POST('email')
        age = request.POST('age')

    author_info = Author.objects.latest('author_id')
    log.debug("test:%s",author_info.author_id)
    author = Author.objects.filter(author_id=author_info.author_id).update(first_name = first_name,last_name = last_name,email=email,age=age)
        return redirect('/index/')
    else:
        books = Book.objects.get(pk=book_id)
        return render_to_response('editbook.html',{'books':books},{'author':author},context_instance=RequestContext(request))

我收到一个错误

"Traceback (most recent call last):
  File "/usr/local/lib/python2.6/site-packages/django/core/handlers/base.py", line 111, in get_response
    response = callback(request, *callback_args, **callback_kwargs)
  File "/root/Samples/DemoApp/DemoApp/views.py", line 70, in editbook
    return render_to_response('editbook.html',{'books':books},{'author':author},context_instance=RequestContext(request))
UnboundLocalError: local variable 'author' referenced before assignment.
4

3 回答 3

3

看起来您在 if 子句中分配了 author 值,同时调用它以返回 else 块。该错误只是说您执行了 else 块(例如 request.POST 为 None)。我所需要的就是在 if 语句之前添加默认值或移动分配。例如,您可以执行以下操作:

def editbook(request, book_id):
    log.debug("test....")
    author = Author.objects.filter(author_id=author_info.author_id)
    books=Book.objects.filter(book_id=book_id)
    if request.POST:
        book_name =request.POST['book_name']
        publisher_name =request.POST['publisher_name']
        books=Book.objects.filter(book_id=book_id).update(book_name=book_name, publisher_name=publisher_name)
        first_name = request.POST('first_name')
        last_name = request.POST('last_name')
        email = request.POST('email')
        age = request.POST('age')

        author_info = Author.objects.latest('author_id')
        log.debug("test:%s",author_info.author_id)
        author = Author.objects.filter(author_id=author_info.author_id).update(first_name = first_name,last_name = last_name,email=email,age=age)
        return redirect('/index/')
    else:
        books = Book.objects.get(pk=book_id)
        return render_to_response('editbook.html',{'books':books},{'author':author},context_instance=RequestContext(request))
于 2013-03-05T06:27:32.513 回答
1

您的代码格式有点偏离,但似乎只有在语句为真author时才分配一个值。If如果它是假的,你试图在author尚未设置时返回该值。

于 2013-03-05T06:26:45.737 回答
0

您的问题是,author仅在条件为真时才被定义if,但您在块中使用它,当条件失败else时将运行。if它与此相同:

def foo(z=None):
    if z:
        i = 'hello'
    else:
        print i


foo()

当您执行上述操作时,因为zis Noneif条件失败,并且i未分配值。由于if条件失败,else子句运行,它试图打印i尚未定义的内容。

于 2013-03-05T06:33:42.020 回答