19

我是 django 新手,我完成了 djangoproject.com 上的 4 部分教程

我的问题是我想在我的投票应用程序上进行登录身份验证。我使用了装饰器@login_required,它工作正常,但在我的views.py 下我只有 vote() 方法。

我在“投票文件夹”下的views.py

from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth.decorators import login_required
from django.views.decorators.cache import never_cache
from django.core.urlresolvers import reverse
from django.template import RequestContext
from polls.models import Poll, Choice


@login_required
@never_cache
def vote(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    try:
        selected_choice = p.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        return render_to_response('polls/detail.html', {
            'poll': p,
            'error_message': "You didn't select a choice.",
        }, context_instance=RequestContext(request))
    else:
        selected_choice.votes += 1
        selected_choice.save()
        return HttpResponseRedirect(reverse('poll_results', args=(p.id,)))
    return HttpResponse("You're voting on poll %s." % poll_id) 

我在“投票文件夹”下的 urls.py

from django.conf.urls.defaults import patterns, include, url
from django.views.generic import DetailView, ListView
from polls.models import Poll

urlpatterns = patterns('',
    url(r'^$',
        ListView.as_view(
            queryset = Poll.objects.order_by('-pub_date')[:5],
            context_object_name = 'latest_poll_list',
            template_name = 'polls/index.html'), name='poll_lists'),
    url(r'^(?P<pk>\d+)/$',
        DetailView.as_view(
            model = Poll,
            template_name = 'polls/detail.html'), name='poll_details'),
    url(r'^(?P<pk>\d+)/results/$',
        DetailView.as_view(
            model = Poll,
            template_name = 'polls/results.html'), name = 'poll_results'),
    url(r'^(?P<poll_id>\d+)/vote/$', 'polls.views.vote'),
)

在我的 urls.py 下,我使用了通用视图。

问题是:我将如何将登录要求放在民意调查应用程序的“索引”下。以便用户在查看可用投票之前先登录。

当前是:我在views.py和方法vote()下使用了需要登录,投票后需要登录。

任何人都可以帮助我吗?

谢谢,贾斯汀

4

2 回答 2

28

第一种方法

在 urls.py 中:

urlpatterns = patterns('',
    url(r'^$',
        login_required(ListView.as_view(
            queryset = Poll.objects.order_by('-pub_date')[:5],
            context_object_name = 'latest_poll_list',
            template_name = 'polls/index.html'), name='poll_lists')),
)

第二种方法

在views.py中:

class IndexView(ListView):
    queryset = Poll.objects.order_by('-pub_date')[:5]
    context_object_name = 'latest_poll_list'
    template_name = 'polls/index.html'

    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):        
        return super(IndexView, self).dispatch(request, *args, **kwargs)

然后在 urls.py

urlpatterns = patterns('',
        url(r'^$',
            IndexView.as_view(), name='poll_lists'),
    )
于 2012-04-23T05:22:24.183 回答
17

只是提供一个可能更新的答案,

我会将它们移动到视图文件并使用LoginRequiredMixin

from django.views.generic import (
    ListView,
    DetailView
)
from django.contrib.auth.mixins import LoginRequiredMixin


class PollsListView(LoginRequiredMixin, ListView):
    model = Poll
    template_name = 'polls/index.html'
于 2018-12-20T09:08:48.850 回答