【问题标题】:Python decorator for Django views: Check for a particular setting in UserProfileDjango 视图的 Python 装饰器:检查 UserProfile 中的特定设置
【发布时间】:2010-12-09 20:42:11
【问题描述】:

我想编写一个装饰器,用于我网站上的所有视图,以首先检查登录用户的 UserProfile 是否具有特定设置。在我的情况下,它是 user.get_profile.user_status 并且该值可以是“过期”或“活动”。如果 user_status = "expired" 我想将它们重定向到计费帐户更新页面。如果他们处于活动状态,他们可以通过。

我想成为 @must_be_active@paywall_check 这样的人。

以前从未写过装饰器。关于如何最好地开始的想法?

【问题讨论】:

    标签: python django authentication login decorator


    【解决方案1】:

    首先,阅读这个http://docs.djangoproject.com/en/1.2/topics/auth/#limiting-access-to-logged-in-users-that-pass-a-test

    不写装饰器其实更简单。

    from django.contrib.auth.decorators import user_passes_test
    
    def must_be_active( user ):
        if .... whatever .... 
    
    def paywall_check( user ):
        if .... whatever .... 
    
    @user_passes_test(must_be_active)
    def my_view(request):
        do the work
    
    @user_pass_test(paywall_check)
    def another_view(request):
        do the work
    

    【讨论】:

    • 这对我有用。但是,我没有将此技术应用于视图,而是将此技术应用于我的 urls.py,其中存在其他类似的设置。让他们在这里对我来说更有意义。在您回答之后,这篇相关的博文也有所帮助:jonatkinson.co.uk/djangos-user_passes_test-and-generic-views
    【解决方案2】:

    【讨论】:

      猜你喜欢
      • 2018-10-18
      • 2014-06-07
      • 2014-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-12
      • 2011-05-29
      • 2013-06-07
      相关资源
      最近更新 更多