如何在django中应用login_required()?

时间:2014-07-19 16:53:29

标签: mysql django authentication login

from django.contrib.auth.decorators import login_required
from views import PostListView
urlpatterns = patterns('',
    (r'^test/$', PostListView.as_view(), name='test'),
)

当我这样做时,就好像Django完全忽略了login_required并直接进入模板。我有正确的身份验证设置。我可以在MySQL数据库中注册新帐户并成功登录/验证。现在我只想将一些页面限制为注册用户。并且在登录时基本保持登录状态。就像一个真实的网站。

编辑:

views.py

from django.shortcuts import redirect, get_object_or_404, render, render_to_response
from django.views.generic import ListView, DetailView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.views.generic.base import View, TemplateView
from django.core.context_processors import csrf
from models import *
from forms import *
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator

class PostListView(ListView):
    model = Post
    context_object_name = "post_list"

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

    def get_template_names(self):
        return ["app/list.html"]

    def get_queryset(self):
        posts = Post.objects
        if 'all_posts' not in self.request.GET:
            posts = posts.filter(is_published=True)                                                         
        return posts 

2 个答案:

答案 0 :(得分:1)

只需将View子类化并使用如下:

from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
class PostListView(ListView):
      @method_decorator(login_required)
      def dispatch(self, *args, **kwargs):
            return super(PostListView, self).dispatch(*args, **kwargs)

网址应该是;

urlpatterns = patterns('',
    (r'^test/$', PostListView.as_view(), name='test'),
)

答案 1 :(得分:1)

我更喜欢这种方式,把装饰器放在网址

urls.py

from django.conf.urls import patterns, include, url
from django.contrib.auth.decorators import login_required
from app.views import MyView

urlpatterns = patterns('',
url(r'^app/url/action/(?P<pk>\d+)/$', login_required(MyView.as_view()),
    name='my_view_action'),
)