Django - 通过ManyToManyKey从django.contrib的User类访问模型

时间:2013-08-18 14:00:00

标签: django django-views

我正在一个Tuts +课程中教授的Django黑客新闻克隆[Git Repo]

views.py文件中,对于投票视图,我尝试使用此代码通过检查用户是否已经喜欢该故事来提高安全性。

@login_required
def vote(request):
    story = get_object_or_404(Story, pk=request.POST.get('story'))
    user = request.user
    if user.is_authenticated() and story not in user.liked_stories:
        story.points += 1
        story.save()
        user.liked_stories.add(story)
        user.save()
    return HttpResponse()

但它给了我这个错误:

NameError: global name 'liked_stories' is not defined
[18/Aug/2013 19:26:43] "POST /vote/ HTTP/1.1" 500 11148

我可以在user.liked_stories视图中使用index,为什么不在vote视图中使用?

错误:

Internal Server Error: /vote/
Traceback (most recent call last):
  File "/home/sourabh/.virtualenvs/django/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 115, in get_response
    response = callback(request, *callback_args, **callback_kwargs)
  File "/home/sourabh/.virtualenvs/django/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 25, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/home/sourabh/Code/django_apps/HackerNews/stories/views.py", line 53, in vote
    if user.is_authenticated() and story not in liked_stories:
NameError: global name 'liked_stories' is not defined
[18/Aug/2013 20:08:35] "POST /vote/ HTTP/1.1" 500 11161

1 个答案:

答案 0 :(得分:0)

你去了:

if user.is_authenticated() and story not in liked_stories:

在此行中引发错误。您发布的代码与您正在执行的代码不同。