[Django]-Django Generic Views using decorator login_required

29๐Ÿ‘

โœ…

1nd approach

In 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')),
)

2nd approach

In 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)

then in urls.py

urlpatterns = patterns('',
        url(r'^$',
            IndexView.as_view(), name='poll_lists'),
    )
๐Ÿ‘คSan4ez

19๐Ÿ‘

Just providing a potentially more up-to-date answer,

I would move them to a views file and use the 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'
๐Ÿ‘คDylan Tonks

Leave a comment