繁体   English   中英

需要 Django wagtail 登录不起作用

[英]Django wagtail login required not working

我正在研究 wagtailcms。我只想在用户登录时显示一个页面。我尝试过 LoginRequiredMixin,@method_decorator(login_required, name='dispatch') 但没有任何效果。请帮忙

from django.contrib.auth.decorators import login_required
@login_required(login_url='/login/')
class LessonListPage(RoutablePageMixin, Page):
""" Lists all the lessons on one page """

    template = "lesson/lesson_list_page.html"

    custom_title = models.CharField(
    max_length=100,
    blank=False,
    null=False,
    help_text='Overwrites the default title',
    )

    content_panels = Page.content_panels + [
    FieldPanel("custom_title"),
    ]

    def get_context(self, request, *args, **kwargs):
        """Adding custom stuff to our context"""
        context = super().get_context(request, *args, **kwargs)
        context["posts"] = LessonDetailPage.objects.live(
        ).public().order_by('-first_published_at')[:10]
        #Change 'public' to adjust which posts are displayed
        context["postcategories"] = Category.objects.all()
        return context

在 Wagtail 页面模型上, serve方法相当于一个视图函数,因此覆盖该方法并添加一个method_decorator应该可以工作。

但是,Wagtail 已经内置了此功能:通过管理员创建页面时提供 的隐私控制允许您将页面设置为仅供登录用户访问。

你可以试试这个:

class LessonListPage(RoutablePageMixin, Page):
""" Lists all the lessons on one page """

    template = "lesson/lesson_list_page.html"

    custom_title = models.CharField(
    max_length=100,
    blank=False,
    null=False,
    help_text='Overwrites the default title',
    )

    content_panels = Page.content_panels + [
    FieldPanel("custom_title"),
    ]

    def get_context(self, request, *args, **kwargs):
        """Adding custom stuff to our context"""
        if request.user.is_authenticated:
           context = super().get_context(request, *args, **kwargs)
           context["posts"] = LessonDetailPage.objects.live(
    ).public().order_by('-first_published_at')[:10]
           #Change 'public' to adjust which posts are displayed
           context["postcategories"] = Category.objects.all()
           return context
        else:
           return redirect('/')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM