我的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.
答案 0 :(得分:3)
看起来你在if子句中分配了作者值,同时在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))
答案 1 :(得分:1)
您的代码格式有点偏,但如果author
语句为true,则If
只会被赋予一个值。如果它是假的,那么当它尚未设置时,你试图返回author
值。
答案 2 :(得分:0)
您的问题是author
仅在if
条件为真时定义,但您在else
块中使用它,该块将在if
条件下运行失败。它与此相同:
def foo(z=None):
if z:
i = 'hello'
else:
print i
foo()
执行上述操作时,由于z
为None
,if
条件失败,i
未分配值。由于if
条件失败,运行else
子句,尝试打印尚未定义的i
。