【问题标题】:Restrict unauthorised access in Django在 Django 中限制未经授权的访问
【发布时间】:2020-02-28 04:24:05
【问题描述】:

我在 Django 项目中有各种应用程序,但我只希望登录的用户能够访问这些页面。我如何限制对除作为我的主页的登录页面之外的每个页面的访问。例如,mywebsite.com/home/user 应该只对用户可用,如果有人输入它应该将他们重定向到 mywebsite.com

目前我有两个应用程序,主应用程序和主页应用程序,我在主页应用程序上使用 ClassBased 视图,如何限制对除登录页面以外的所有页面的访问并同时显示消息? p>

我想创建一个模板,用户可以看到其他用户个人资料的详细信息,但不能更改或编辑它们。我该如何执行上述步骤

提前致谢!

【问题讨论】:

  • 你试过了吗?

标签: django django-models django-views django-templates


【解决方案1】:

根据Docs,您可以使用@login_required 装饰基于类的视图

from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator

@method_decorator(login_required, name='dispatch')
class ClassBasedView(View): 
    ...
    ...

由于你使用的是基于类的视图,你需要添加方法装饰器,否则你可以直接使用@logine_required。

问题的另一部分又与此分开。

【讨论】:

    【解决方案2】:

    你可以试试这个,方法很简单

    from django.contrib.auth.decorators import login_required
    
    
    @login_required
    def my_view(request):
        return HttpResponse()
    

    使用 @login_required 意味着用户必须登录才能访问该视图

    或者如果你想使用类,那么试试这个

    from django.contrib.auth.mixins import LoginRequiredMixin
    from django.views.generic import TemplateView
    
    
    class RestrictedView(LoginRequiredMixin, TemplateView):
        template_name = 'foo/restricted.html'
        raise_exception = True 
        permission_denied_message = "You are not allowed here."
    

    【讨论】:

    • 谢谢!是的,我试过了,它奏效了。感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-25
    • 2015-03-05
    • 1970-01-01
    • 2012-07-12
    • 1970-01-01
    • 2020-05-27
    • 1970-01-01
    相关资源
    最近更新 更多