我正在尝试允许用户在注销时收藏视频。我正在使用@login_required强制用户登录,将视频保存到他们的帐户,然后重定向回他们所在的页面。我收到错误说
UnboundLocalError at /loggedout_fav/
local variable 'video' referenced before assignment
<form method = 'post' action = '/loggedout_fav/'> {% csrf_token %}
<input type="hidden" value="{{video}}" name = "video_add_loggedout"/>
<input type='submit' value='Login to plate this video'/>
</form>
url(r'^loggedout_fav/', 'loggedout_fav'),
def loggedout_fav(request):
if 'video_add_loggedout' in request.POST:
video = request.POST['video_add_loggedout']
print video
print 'test'
try:
s = Everything.objects.get(profile = request.user, video = request.POST['video_add_loggedout'], playlist = 'Favorites', platform = 'youtube')
print "already exists"
except:
p = Everything(profile = request.user, video = request.POST['video_add_loggedout'], playlist = 'Favorites', platform = 'youtube')
p.save()
return HttpResponseRedirect(reverse('reserve.views.trending_video_player', kwargs={'author':'youtube', 'video':video}))
def trending_video_player(request,author,video):
...
答案 0 :(得分:0)
您使用'id'代替'name'!所以这永远不会是真的:
if 'video_add_loggedout' in request.POST:
并且video
永远不会被设置,所以它会窒息(你应该发布堆栈跟踪BTW,我不得不改变它):
return HttpResponseRedirect(reverse('reserve.views.trending_video_player', kwargs={'author':'youtube', 'video':video}))
首先你可以修复你的Python,如下所示:
def loggedout_fav(request):
if 'video_add_loggedout' not in request.POST:
return HttpResponseBadRequest()
video = request.POST['video_add_loggedout']
try:
s = Everything.objects.get(profile = request.user, video = request.POST['video_add_loggedout'], playlist = 'Favorites', platform = 'youtube')
print "already exists"
except:
p = Everything(profile = request.user, video = request.POST['video_add_loggedout'], playlist = 'Favorites', platform = 'youtube')
p.save()
return HttpResponseRedirect(reverse('reserve.views.trending_video_player', kwargs={'author':'youtube', 'video':video}))
当然,修复你的HTM,这个:
<input type="hidden" value="{{video}}" id = "video_add_loggedout"/>
应该是:
<input type="hidden" value="{{video}}" name="video_add_loggedout"/>
答案 1 :(得分:0)
将值保存到会话中。 https://docs.djangoproject.com/en/dev/topics/http/sessions/
确保在登录用户之前获取会话中的值,这样您就不会丢失它们。
答案 2 :(得分:0)
我相信jpic所说的可能就是问题所在。我发布了一个单独的答案来澄清问题:UnboundLocalError是一个python错误,意味着代码中的某个位置在定义变量之前访问变量。
在您的'loggedout_fav'视图代码中,我看到您尝试访问最后一行中的'video'变量。当if 'video_add_loggedout' in request.POST
语句不为True(因此嵌套块未执行)时,'video'变量将不会被初始化,并且将引发此异常。实际上,这意味着您尝试访问视图而不发布“video_add_loggedout”变量。我会按如下方式重新组织视图:
def loggedout_fav(request):
try:
Everything.objects.get_or_create(profile=request.user, video=request.POST['video_add_loggedout'], playlist='Favorites', platform='youtube')
except KeyError:
#do something when the variable is not set. eg:
return HttpResponseBadRequest()
return HttpResponseRedirect(reverse('reserve.views.trending_video_player', kwargs={'author':'youtube', 'video':request.POST['video_add_loggedout']}))
上面还演示了如何使用get_or_create
方法清理代码。